tomatopipps
tomatopipps

Reputation: 297

javascript switch-case for 2 booleans

I have 2 boolean values, boolA and boolB. I want a single switch-case statement that takes each of the four possible combinations, i.e. something like

switch(boolA boolB){
  case 0 0:
    [do something];
  case 0 1:
    [do something else];
  case 1 0:
    [do another thing];
  case 1 1:
    [do the other thing];

Basically I want the switch-case to interpret the two booleans as a single 2 bit number.

Update: I decided to just use normal if-else stuff.

Upvotes: 1

Views: 5566

Answers (5)

jcoleau
jcoleau

Reputation: 1200

ES6 Alternative combined with the unary + operator:

switch (`${+boolA}${+boolB}`) {
    case "00": //logic
      break;
    case "10": //logic
      break;
    case "01": //logic
      break;
    case "11": //logic
      break;
  }

Upvotes: 0

tomatopipps
tomatopipps

Reputation: 297

I decided to use

switch(parseInt(boolB.toString()+boolA,2)){
  case 0://neither
    [do something];
  case 1://boolA
    [do something else];
  case 2://boolB
    [do another thing];
  case 3://both
    [do the other thing];
}

which parses the booleans as bits in a binary number.

Upvotes: 3

Michael B.
Michael B.

Reputation: 351

An alternative implementation would be to not use a switch statement at all. You could create a javascript object mapping boolean values as keys to function objects.

var truthTable = {
    false: {
        false: falsefalseFunc,
        true: falsetruefunc
    },
    true: {
        false: truefalseFunc,
        true: truetrueFunc
    }
}

Where falsefalseFunc, falsetrueFunc, etc... are function objects. Then you can call it like:

truthTable[boolA][boolB]();

Upvotes: 2

Steve Mitcham
Steve Mitcham

Reputation: 5313

The Mozilla MDN docs refer to this method to achieve what you want by making the switch evaluate true and then putting logic in switch statements

switch (true) { // invariant TRUE instead of variable foo
    case a && b:
    //logic
        break;
    case a && !b:
    //logic
        break;
    case !a && b:
    //logic
        break;
    case !a && !b:
    //logic
        break;
}

I would just use regular if-else if logic to make things clearer.

Upvotes: 7

T.J. Crowder
T.J. Crowder

Reputation: 1074989

I don't think I'd do that.

But if you really want to, you can use boolA + " " + boolB:

switch(boolA + " " + boolB){
  case "false false":
    [do something];
    break;
  case "false true":
    [do something else];
    break;
  case "true false":
    [do another thing];
    break;
  default: // "true true"
    [do the other thing];
    break;
}

Or if you prefer numbers, (10 * boolA) + boolB:

switch((10 * boolA) + boolB){
  case 0:
    [do something];
    break;
  case 1:
    [do something else];
    break;
  case 10:
    [do another thing];
    break;
  default: // 11
    [do the other thing];
    break;
}

Both of those implicit conversions are guaranteed in the spec.

Upvotes: 1

Related Questions