Multiple variables with a switch (Javascript) [duplicate] - javascript

I am a newbie when it comes to JavaScript and it was my understanding that using one SWITCH/CASE statements is faster than a whole bunch of IF statements.
However, I want to use a SWITCH/CASE statement with two variables.
My web app has two sliders, each of which have five states. I want the behavior to be based on the states of these two variables. Obviously that is a whole heck of a lot of IF/THEN statements.
One way I thought about doing it was concatenating the two variables into one and then I could SWITCH/CASE that.
Is there a better way of accomplishing a SWITCH/CASE using two variables ?
Thanks !

Yes you can also do:
switch (true) {
case (var1 === true && var2 === true) :
//do something
break;
case (var1 === false && var2 === false) :
//do something
break;
default:
}
This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.

How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."
// Declare slider's state "enum"
var SliderOne = {
A: 1,
B: 2,
C: 4,
D: 8,
E: 16
};
var SliderTwo = {
A: 32,
B: 64,
C: 128,
D: 256,
E: 512
};
// Set state
var s1 = SliderOne.A,
s2 = SliderTwo.B;
// Switch state
switch (s1 | s2) {
case SliderOne.A | SliderTwo.A :
case SliderOne.A | SliderTwo.C :
// Logic when State #1 is A, and State #2 is either A or C
break;
case SliderOne.B | SliderTwo.C :
// Logic when State #1 is B, and State #2 is C
break;
case SliderOne.E | SliderTwo.E :
default:
// Logic when State #1 is E, and State #2 is E or
// none of above match
break;
}
I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.

var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
case "something|something_else":
...
break;
case "something|...":
break;
case "...|...":
break;
}
If you have 5 possibilities for each one you will get 25 cases.

First, JavaScript's switch is no faster than if/else (and sometimes much slower).
Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:
var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
case "foo-bar": ...
...
}
But, personally, I would rather see a set of if/else statements.
Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

If the action of each combination is static, you could build a two-dimensional array:
var data = [
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]
];
The numbers in above example can be anything, such as string, array, etc. Fetching the value is now a one-liner (assuming sliders have a value range of [0,5):
var info = data[firstSliderValue][secondSliderValue];

You could give each position on each slider a different binary value from 1 to 1000000000
and then work with the sum.

Yeah, But not in a normal way. You will have to use switch as closure.
ex:-
function test(input1, input2) {
switch (true) {
case input1 > input2:
console.log(input1 + " is larger than " + input2);
break;
case input1 < input2:
console.log(input2 + " is larger than " + input1);
default:
console.log(input1 + " is equal to " + input2);
}
}

I did it like this:
switch (valueA && valueB) {
case true && false:
console.log(‘valueA is true, valueB is false’)
break;
case ( true || false ) && true:
console.log(‘valueA is either true or false and valueB is true’)
break;
default:
void 0;
}

Related

How to check if words are there in a string using switch statements?

I have this code -
const myFunc = () => {
switch (transcript) {
case transcript.split(" ").includes("hello"):
case transcript.split(" ").includes("hey"):
case "hi":
case "hallo":
const greetingArray = ["Hello!", "Hi!"];
const randomItem =
greetingArray[Math.floor(Math.random() * greetingArray.length)];
setMyVar(randomItem);
TTS(myVar, "english");
break;
case "bye":
TTS("Goodbye", "english");
break;
}
return myVar;
};
As you can see, I tried to check if the words hey and hello is there in the transcript, but it isn't working.
How can I correct this?
Thanks in advance!!
.includes returns true/false so it would look like case true: case: false which is pointless code. It compiles (pseudo code) to something weird like this:
val = "hello";
if (val: string == (val.split(" ").includes("hello"): boolean) || val == "hi" || etc) {
... do set var stuff
}
case "word": does work, however it would mean the transcript can ONLY and must be character by character identical to the "word".
So the includes do nothing, and because the following case's say "hallo" and "hi", hello/hey will not trigger any case and because theirs no default event it just escapes.
Your fix would be changing both your transcript.split.includes to simply "hello" and "hey".

javascript: check if variable is a specific letter

Very basic javascript, i'm a complete beginner trying to construct an if statement to check if a variable is a specific letter
more specifically, if a user input for a variable is "P", "M" or "G"
i'm using
if (variable = P) {
statement
}
but doesn't seem to be working
thanks in advance
In addition to forgetting the quotes around the letter "P", you've used the assignment operator =, instead of the comparator ==.
Check this out:
var name = "Carolyn";
console.log(name);
# "Carolyn"
var name_is_carolyn = (name == "Carolyn");
console.log(name_is_carolyn);
# true
Changing your code to this should help:
if (variable == "P") {
// statement
}
if(variable == 'P' || variable == 'G' || variable == 'M') {
// do something
}
take care, it's case sensitive without using toLowerCase or toUpperCase on the string.
anther way is:
switch(variable.toLowerCase()) {
case 'p':
// do something for p
break;
case 'm':
case 'g':
// do something for m and g (no break; in m case)
break;
default:
// no match, so do something else
}
Here's how you can do it in JS:
TextLetter=function(txt,letter){
try{
var TXT=txt.split(letter);
if(TXT.length>0)
return true;
else
return false;
}catch(err){
return false;
}
}
TextLetter(prompt("Type in text","TEXT"),prompt("Look for the character or phrase...","?"));
I didn't test this yet, but should be helpful

Numeric comparison failure in a switch statement

"original post" : This function should compare the value of 'a' with several other values, but always defaults. My test shows that the value of 'a' or 'b' is never changed. Do I have the case a > statement incorrect or elsewhere?
Now I understand that I can not use comparison in the case statement:
Should I use a bunch of if statements and a while (a <> = 0) to do the multiple checking and decrementing?
The snippit below shows 'a' with a particular value. In the full function, actually 'a' gets a value from a random number in another function. It must be checked against 16 possible values and decremented, then rechecked until it finally reaches 0. The comparison values are actually powers of 2 (1 through 16).
function solution() {
var a = 18000;
var b = 0;
switch (a) {
case a > 30000:
a = a - 30000;
b = b++;
break;
case a > 16000:
b = b++; a = a - 16000;
break;
case a > 8000:
b = b++; a = a - 8000;
break;
default:
c = "defaulted!, Why?";
break;
}
window.alert (a + " " + b + " " + c);
}
Don't use switch for range checks like this. It's possible with
switch (true) {
case (a > 30000):
a = a - 30000;
b = b++;
but just don't do that.
Use if/else instead. While switch is really just an abstract if/else construct, use it for things like this:
switch(a){
case 1: ...
}
In a nutshell, you can't use boolean expressions in switch case labels. You'll need to rewrite the code as a series of if statements.

Why is this switch statement not behaving as predicted?

I have the following switch block:
var str = 'matches[pw1]';
switch (str)
{
case (str.indexOf('matches') > -1) :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
What I want is, that if str contains the word 'matches', then it should run the first case block, otherwise the default block.
However when I run this, the output I get is '0', and then 'no', meaning the default block is running despite the conditions for the first case being met.
Any ideas what's wrong?
Your case is likely testing whether (str.indexOf('matches') > -1) == str.
EDIT:
It might be valuable to understand exactly what switch and case mean. One of Javascript's ancestors, C, commonly used switch to replace blocks of code where a primitive was being compared against a list of values (often from an enumeration, or a series of literals). So instead of:
if (type == ENABLE_FRAMISTAN)
{
enable_framistan();
}
else if (type == ENABLE_FROBSOSTICATOR)
{
enable_frobnosticator();
}
else if (type == DISABLE_BAZTICULATOR)
{
disable_bazticulator();
}
else
{
assert(false);
}
you could instead write:
switch (type)
{
case ENABLE_FRAMISTAN: enable_framistan(); break;
case ENABLE_FROBNOSTICATOR: enable_frobnosticator(); break;
case DISABLE_BAZTICULATOR: disable_bazticulator(); break;
default: assert(false); break;
}
...which might make it easier to digest (and or spot errors in) a large block of code which effectively mapped type values to functions being called (or some such). Your designated usage, checking to see whether a string matches any of a number of potential (exclusive with one another?) patterns, does not map as well to switch. If it were merely equality being tested, it would work well, but your condition is more sophisticated than switch was designed to express. Any way that you manage to preserve switch with your feature set will likely require less-than-obvious code.
Why not use an if statment? try something like this:
var str = 'matches[pw1]';
if(str.indexOf('matches') > -1) {
console.log('yes');
break;
}else{
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
It should work since you don't have alot of cases anyways. I don't think you can do a comparing in cases.
What I want is, that if str contains the word 'matches', then it should run the first case block, otherwise the default block.
You cannot do that with a switch statement. A switch statement compares the result of evaluating the switch expression (in this case str) with the values of the case labels. The case labels can be expressions (as in your example), but if they are the expressions are evaluated and then compared against the value above using ===. (That's what the ECMAScript 5.1 spec says ...)
So what your code is actually doing for that case is (roughly speaking):
evaluate (str.indexOf('matches') > -1) which gives you true or false
compare true or false with the value of str ... which fails and the case body isn't executed.
Now I think you could make your approach work as follows:
case (str.indexOf('matches') > -1 ? str : '') :
console.log('yes');
break;
but that stinks from a code readability perspective (IMO).
You could do this:
console.log( str.indexOf( 'matches' ) > -1 ? 'yes' : 'no' );
You should know the basic usage of switch. I think you mistakenly use Switch. Try to use it as following:
var str = 'matches[pw1]';
str = str.indexOf('matches');
switch (str)
{
case -1 :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
Please look at the Following URL http://www.w3schools.com/js/js_switch.asp
If the above is not suitable for your logic, use if.. else if ...
http://www.w3schools.com/js/js_if_else.asp

jquery Using ranges in switch cases?

Switch cases are usually like
Monday:
Tuesday:
Wednesday:
etc.
I would like to use ranges.
from 1-12:
from 13-19:
from 20-21:
from 22-30:
Is it possible? I'm using javascript/jquery by the way.
you could try abusing the switch fall through behaviour
var x = 5;
switch (x) {
case 1: case 2: case 3: case 4: ...
break;
case 13: case 14: case 15: ...
break;
...
}
which is very verbose
or you could try this
function checkRange(x, n, m) {
if (x >= n && x <= m) { return x; }
else { return !x; }
}
var x = 5;
switch (x) {
case checkRange(x, 1, 12):
//do something
break;
case checkRange(x, 13, 19):
...
}
this gets you the behaviour you would like. The reason i return !x in the else of checkRange is to prevent the problem of when you pass undefined into the switch statement. if your function returns undefined (as jdk's example does) and you pass undefined into the switch, then the first case will be executed. !x is guaranteed to not equal x under any test of equality, which is how the switch statement chooses which case to execute.
Late to the party, but upon searching for an answer to the same question, I came across this thread. Currently I actually use a switch, but a different way. For example:
switch(true) {
case (x >= 1 && x <= 12):
//do some stuff
break;
case (x >= 13 && x <= 19):
//do some other stuff
break;
default:
//do default stuff
break;
}
I find this a lot easier to read than a bunch of IF statements.
You can make interesting kludges. For example, to test a number against a range using a JavaScript switch, a custom function can be written. Basically have the function test a give n value and return it if it's in range. Otherwise returned undefined or some other dummy value.
<script>
// Custom Checking Function..
function inRangeInclusive(start, end, value) {
if (value <= end && value >= start)
return value; // return given value
return undefined;
}
// CODE TO TEST FUNCTION
var num = 3;
switch(num) {
case undefined:
//do something with this 'special' value returned by the inRangeInclusive(..) fn
break;
case inRangeInclusive(1, 10, num):
alert('in range');
break;
default:
alert('not in range');
break;
}
</script>
This works in Google Chrome. I didn't test other browsers.
Nope, you need to use an if/else if series to do this. JavaScript isn't this fancy. (Not many languages are.)

Categories