Javascript switch case keeps skipping to the default case - javascript

My Switch case keeps on going to default.
The condition is from the intersectionWord which outputs a specific keyword from an array which matches up to a word in the trigger word array aka an intersectionWord.
const TriggerWord = ["weather", "add", "multiply", "divide", "subtract", "hi", "hello",];
const intersectionWord = TriggerWord.filter(element => request.requestContent.includes(element));
And the objective was to pass that trigger word into the switch statement to evaluate if any of those cases match up. If they do match up it should output an alert. But currently it just seems to go straight to the default case every time.
I don't know where it is going wrong.
switch (intersectionWord) {
case TriggerWord[0].toString:
alert("Checking the weather");
break;
case TriggerWord[1].toString:
alert("Doing the math");
break;
case TriggerWord[2].toString:
alert("Doing multiplication");
break;
case TriggerWord[3].toString:
alert("Doing the division");
break;
case TriggerWord[4].toString:
alert("Doing the subtraction");
break;
case TriggerWord[5].toString:
alert("Just saying Hello");
break;
case TriggerWord[6].toString:
alert("Just saying Hello");
break;
default:
alert("I couldn't find a TriggerWord");
}

As noted in the comments, there are two problems with your code:
You're missing the () after .toString so it will call the function; also, it's not necessary to use .toString(), since they're already strings.
intersectionWord is an array, so it will never be equal to any of the strings in TriggerWords.
Instead of the switch/case statement, consider using an object:
const messages = {
weather: "Checking the weather",
add: "Doing the math",
multiply: "Doing multiplication",
...
}
Then you can loop over intersectionWords, looking up the corresponding message:
intersectionWords.forEach(word => alert(messages[word]))
Or you could combine them all into a single message:
let actions = intersectionWords.map(word => messages[word]).join(", ");
if (actions) {
alert(actions);
} else {
alert("No matching activity");
}

Related

How to correctly loop querySelectorAll for hyperlink translation (JavaScript)

Hello!
Am working on an author's hyperlink translation in several languages.
Could someone help me correctly loop querySelectAll which translates some text for all elements collected by it, because it only translates the first hyperlink and not them all.
switch (pLang) {
case "lv":
document.querySelectorAll('[title="John Davis publikācijas"]').innerHTML = "Džons Deivis";
break;
case "ru":
document.querySelectorAll('[title="Записи John Davis"]').innerHTML = "Джон Дэйвис";
break;
}
You could use a forEach to modify all the elements instead of just the first one:
switch (pLang)
{
case "lv":
[... document.querySelectorAll('[title="John Davis publikācijas"]')].forEach((element)=>
{
element.innerHTML = "Džons Deivis";
});
break;
case "ru":
[... document.querySelectorAll('[title="Записи John Davis"]')].forEach((element)=>
{
element.innerHTML = "Джон Дэйвис";
});
break;
}

Is There A Way to Avoid Nested Switch Statements

I am working on a React project using nested switch statements to route the user depending on their selection. The first case has two more nested switch statements. The second case has one nested switch statement. Is there another way I could do this without all the nested switch statements? Any help is greatly appreciated.
clickConfirm = () => {
switch (this.props.serviceType) {
case 'car_service':
switch (this.props.loadType) {
case 0:
switch (this.props.photoMode) {
case 0:
this.props.push('/payment/');
break;
case 1:
this.props.push('/payment/');
// capture image here
break;
case 2:
this.props.push('/capture/');
break;
}
break;
case 1:
switch (this.props.photoMode) {
case 0:
this.props.history.push('/address/');
this.props.setToPhoneNumber(false);
break;
case 1:
this.props.history.push('/address/');
this.props.setToPhoneNumber(false);
// capture image here
break;
case 2:
this.props.push('/capture/');
break;
}
break;
case 2:
this.props.history.push('/phone/');
this.props.setToPhoneNumber(true);
break;
}
break;
case 'phone_service':
switch (this.props.photoMode) {
case 0:
this.props.history.push('/address/');
break;
case 1:
this.props.history.push('/address/');
// capture image here
break;
case 2:
this.props.history.push('/capture/');
break;
}
break;
}
};
You can store the data in an object like this:
const SERVICES = {
'car_service': {
0: {
0: ()=> {
this.props.push('/payment/');
}
}
}
}
Then you can replace the switch part with:
clickConfirm = () => {
SERVICES[this.props.serviceType][this.props.loadType][this.props.photoMode]();
}
I don't suggest this, seems like your component should maybe take in the option directly or otherwise be broken up instead of combined in the way it is.
But without knowing your use-case or why you're "pushing to props"(?), purely to "flatten" your condition, you could combine the various values and enumerate the known combinations.
NOTE: I haven't tested this or attempted to map this to your conditions exactly, but the general idea...
const combined = [this.props.serviceType, this.props.photoMode, this.props.loadType || 'NA'].join('|');
switch (combined) {
case 'car_service|0|0':
this.props.push('/payment/'); break;
case 'car_service|1|0':
this.props.push('/payment/'); break; // capture image here
case 'car_service|2|0':
this.props.push('/capture/'); break;
case 'car_service|0|1':
this.props.push('/address/'); this.props.setToPhoneNumber(false); break;
case 'car_service|1|1':
this.props.push('/address/'); this.props.setToPhoneNumber(false); break; // capture image here
case 'car_service|2|1':
this.props.push('/capture/'); break;
case 'car_service|0|2':
case 'car_service|1|2':
case 'car_service|2|2':
this.props.history.push('/phone/'); this.props.setToPhoneNumber(true); break;
case 'phone_service|0|NA':
this.props.history.push('/address/'); break;
case 'phone_service|1|NA':
this.props.history.push('/address/'); break; // capture image here
case 'phone_service|2|NA':
this.props.history.push('/address/'); break;

Switch statement to match several cases

I want to write a switch statement that will go through first 2 cases if they are both true. If not, only match the one that is true.
var vehicle = {main: false, detail: false};
switch(true) {
case (states.data.currentState.indexOf('main.vehicle') !== -1):
vehicle.main = true;
break;
case (states.data.currentState === 'main.vehicle.detail):
vehicle.detail = true;
break;
}
My problem is that after first break the switch statement ends and doesn't go to case 2. However if I remove break from first case it will jump to case 2 and apply vm.vehicle.detail = true; even though the case condition isn't met.
So if I remove break in the first case, my object will look like this anyway
{ main: true, detail: true }
If I don't it will look like this
{ main: true, detail: false }
How do I meet both conditions on single run of the switch?
Why not just take the comparisons as values for the object?
var vehicle = {
main: states.data.currentState.indexOf('main.vehicle') !== -1,
detail: states.data.currentState === main.vehicle.detail
};
ES6
var vehicle = {
main: states.data.currentState.includes('main.vehicle'),
detail: states.data.currentState === main.vehicle.detail
};

Switch statement not working within JSX (React.js)

I am trying to make my switch work within JSX, but for some reason it doesn't work.
Every output has an ID, which is I. Now I am trying to make a switch statement with I, but it will always return the default value.
Why?
My code:
{(() => {
switch (i) {
case "0": return "{indents}";
case "1": return "{indents2}";
case "2": return "{indents3}";
default: return "{indents3}";
}
})()}
This is all within a div with attribute key={i}.
I would recommend maps instead. Maps/objects are type insensitive. It will also reduce execution complexity:
const map = {
0: indents,
1: indents2,
2: indents3
}
<div>{map[i] || indents3}</div>
Alternatively, since you are using 0,1,2.., you can also have it as an array.
const map = [indents, indents2, indents3];
<div>{map[i] || indents3}</div>

Why isn't my switch block (switching on $(e.target) .attr("class")) working?

I am trying to figure out why this code doesn't work..
All i want is to have simple event delegation to assign one event listener.
it only alerts, it doesn't animate.
Please let me know whats wrong here:
$(document).ready(function() {
var img = $("img");
$("span").click(function(e){
var targetClicked = $(e.target).attr('class');
//the alert works fine
alert(targetClicked)
switch(targetClicked){
// i deleted the rest of the cases
case d:img.stop(false,true);
break;
case e:img.slideDown().animate({"width":200, height:200, opacity:0.4,});
break;
//nothings works here as well
case f:alert("hi");
break;
}
});
});
What are d and e in your switch statement case conditions? The way you're code is written right now, they're being treated as variables and your code is probably blowing up with a "'d' is undefined" error.
If you want to switch on the class names "d" and "e", then you need to use the class names as strings:
switch (targetClicked) {
case "d":
//...
break;
case "e":
// ...
break;
}

Categories

Resources