Can I use a case/switch statement with two variables?

JavascriptSwitch StatementCase

Javascript Problem Overview


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 !

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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.

Solution 6 - Javascript

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];

Solution 7 - Javascript

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

Solution 8 - Javascript

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);
      }
   }

Solution 9 - Javascript

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;
}

Solution 10 - Javascript

Languages like scala&python give to you very powerful stuff like patternMatching, unfortunately this is still a missing-feature in Java...

but there is a solution (which I don't like in most of the cases), you can do something like this:

final int s1Value = 0;
final int s2Value = 0;
final String s1 = "a";
final String s2 = "g";

switch (s1 + s2 + s1Value + s2Value){
    case "ag00": return true;
    default: return false;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser918967View Question on Stackoverflow
Solution 1 - JavascriptaabiroView Answer on Stackoverflow
Solution 2 - JavascriptDashKView Answer on Stackoverflow
Solution 3 - JavascriptHalcyonView Answer on Stackoverflow
Solution 4 - JavascriptDavid WoleverView Answer on Stackoverflow
Solution 5 - JavascriptkittiView Answer on Stackoverflow
Solution 6 - JavascriptJa͢ckView Answer on Stackoverflow
Solution 7 - JavascriptTecBratView Answer on Stackoverflow
Solution 8 - JavascriptParulView Answer on Stackoverflow
Solution 9 - JavascriptMike OxhugeView Answer on Stackoverflow
Solution 10 - JavascriptAndrea CiccottaView Answer on Stackoverflow