javascript switch-case for 2 booleans - javascript

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.

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.

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

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.

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.

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

Related

Switch case match with string

function getFieldType(value){
var type = "";
switch(value){
case "TEXT_BOX":
type=FieldTypeEnum.TEXT_BOX;
break;
case "PASSWORD":
type=FieldTypeEnum.PASSWORD;
break;
case "CHECK_BOX":
type=FieldTypeEnum.CHECK_BOX;
break;
case "RADIO_BUTTON":
type=FieldTypeEnum.RADIO_BUTTON;
break;
case "DROP_DOWN":
type=FieldTypeEnum.DROP_DOWN;
break;
case "SEARCH_CARD_BOX":
type=FieldTypeEnum.SEARCH_CARD_BOX;
break;
case "STATE_DROP_DOWN":
type=FieldTypeEnum.STATE_DROP_DOWN;
break;
case "ID_DROP_DOWN":
type=FieldTypeEnum.ID_DROP_DOWN;
break;
case "GENDER_DROP_DOWN":
type = FieldTypeEnum.GENDER_DROP_DOWN;
break;
default:
type = "";
}
return type;
}
I want to combined three drop down box (STATE_DROP_DOWN, ID_DROP_DOWN, GENDER_DROP_DOWN)into one .
Means I want something like below :
case String.endwith("_DROP_DOWN"):
type=FieldTypeEnum.ID_DROP_DOWN;
break;
Is it possible in JavaScript? If yes then how?
It is possible, in a javascript switch/case statement you can compare for string equality (which evaluates to true or false) or more complex statements which just as when testing for string equality, also evaluate to true or false (e.g. String.endwith("_DROP_DOWN")). However personally I would prefer the following:
STATE_DROP_DOWN:
// intentional fall through
ID_DROP_DOWN:
// intentional fall through
GENDER_DROP_DOWN:
//.. do your stuff
break;
I believe this way it is more clearly through which switch case you are falling in a certain situation.
You can put a ternary operator in the case, and test if it ends with "DROP_DOWN" return value otherwise blank string.
switch(value){
case value.endsWith("_DROP_DOWN") ? value : '' {
type=FieldTypeEnum.ID_DROP_DOWN;
break;
}
}

Match multiple values in a case of a switch

I wonder if I can do a switch whose cases only fall when several values match.
I have an array with values 'X', 'O' or ' '. I want that when some values are 'X', fall through the case.
This is the idea:
switch(numbers.indexOf('X')) {
case 0 && 1 && 2:
//Do something
break;
case 2 && 3 && 4:
//Do something
break;
}
I know that I can do it with if - else easily, but I would like do it with a switch if it is possible.
Thanks!
Likely what you'll want to do is stick the different functions you want to perform in their own section and then call them in each switch case. Sadly switch cases don't let you stack them like that, it would be lovely wouldn't it? Something like:
function a(){};
function b(){};
switch(x){
case 0:
a();
break;
case 1:
a();
break;
case 2:
b();
break;
case 3:
b();
break;
}
Try this one:
switch(variable) {
case 0:
case 1:
case 3:
alert("Found necessary index");
break;
default:
console.log(variable);
break;
}

How do you have a NaN case in a switch statement?

Since NaN === NaN evaluates to false, is it possible to add a NaN case to a switch statement?
For example, let's say I want to make the following switch:
switch(x){
case 1:
case 2:
case 4:
doSomething();
break;
case NaN:
doSomethingElse();
break;
case default:
doADifferentThing();
break;
}
Sending NaN as x will go to the default case. I know there are ways around using NaN in switch statements (e.g. I can surround with an if..else statement and use isNaN), but is there a more direct approach?
I originally wrote i saw only one solution, however during my sleep i came up with a superb solution.
Always keep in mind that a switch does not do implicit type conversion to compare the cases so if you provide a string to the switch statement it will not match to integers in the cases, and vice versa.
If you want to compare to strings and integers you will have to cast your integer to a string first and then compare to strings only.
The superb solution:
As pointed out by WouterH, my initial solution will resolve to default when using a string that contains a number, this is expected behavior for switch statements. But it might be useful to parse the argument in order to overcome this. For that you can use following code:
var x = "1";
switch (isNaN(x) || parseInt(x))
{
case true:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
My initial superb method :
var x = "clearly not a number";
switch(x){
case !isNaN(x) || x:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
isNaN will return true if x where to be a string but it doesn't really matter because true won't evaluate as true to a string because of the above mentioned behavior of the switch statement.
My original solution:
I don't even know what i was thinking, this looks horrible and the indentation is just plain awkward, but thanks for the upvotes !
var x = "clearly not a number";
switch(x){
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
case default:
if (isNaN(x)){
alert("isNaN");
break;
}
alert("default");
break;
}
Brad's solution:
thx to Brad for this one.
I don't really like this because it feels a bit like a hack, that is to say, this isn't how you would expect usage of a case statement, but it does give you the most flexibility, so i'm certain there is a use case for it.
var x = "clearly not a number";
switch(true)
{
case x==1:
alert("1");
break;
case x==2:
alert("2");
break;
case IsNaN(x):
alert("IsNaN");
break;
case default:
alert("default");
break;
}
You could do this (jsFiddle):
var x = "test";
switch (isNaN(x) || x)
{
case true:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
Or if you also want to validate string containing a number (jsFiddle):
var x = "1";
switch (isNaN(x) || parseInt(x))
{
case true:
alert("IsNaN!")
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 4:
alert("4");
break;
default:
alert("default");
break;
}
#helmus's answer is correct and is a good solution.
However, you can maintain the NaN case if you use strings:
switch(x+''){
case "1":
case "2":
case "4":
doSomething();
break;
case "NaN":
doSomethingElse();
break;
default:
doADifferentThing();
break;
}
use toString():
switch (x.toString()) {
case '1':
case '2':
case '4':
console.log('1/2/4');
break;
case 'NaN':
console.log('NaN');
break;
default:
console.log('default');
}

Switch case - else condition

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d = new Date();
var theDay = d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
If the theDay = 5, then we display Finally Friday. I want if theDay !=5, then display 'Finally Something'.. similarly for others too...
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
No.
The switch statement will execute the first matching case, and then keep going (ignoring all further case labels) until it gets to either a break statement or the end of the switch block - but even though you can "fall through" to subsequent cases by omitting the break statement the switch does not provide any mechanism to say "do something when this case isn't matched/executed, but also keep trying to look for a matching case".
What you are describing would normally be done with a series of if/else statements:
var d = new Date(),
theDay=d.getDay(),
matched = false;
if (theDay === 5) {
matched = true;
document.write("Finally Friday");
} else {
// your != 5 case here
}
if (theDay === 6) {
matched = true;
document.write("Super Saturday");
} else {
// your != 6 case here
}
if (theDay === 0) {
matched = true;
document.write("Sleepy Sunday");
} else {
// your != 0 case here
}
// default when none matched:
if (!matched) {
document.write("I'm looking forward to this weekend!");
}
Note that I've added a matched flag to allow the default to work. And note that there are no else if statements because you need every if/else pair to execute.
If you are really determined to use a switch statement you could do something silly like the following:
var d = new Date(),
theDay = d.getDay(),
c,
cases = { // pre-list all the "not" cases
"!5" : true,
"!6" : true,
"!0" : true
};
// add case for theDay and remove the "not" case for theDay (if there is one)
cases[theDay] = true;
if (cases["!" + theDay])
delete cases["!" + theDay];
for (c in cases) {
switch(c) {
case "5":
document.write("Finally Friday");
break;
case "!5":
document.write("Finally Something");
break;
case "6":
document.write("Super Saturday");
break;
case "!6":
document.write("Finally Something - but not 6");
break;
case "0":
document.write("Sleepy Sunday");
break;
case "!0":
document.write("Finally Something - but not 0");
break;
default:
document.write("I'm looking forward to this weekend!");
}
}
If you need the cases to execute in a specific order use an array rather than an object.
Its like switch does a jump to the matching case, if it doesn't match it will jump to what matches. The answer to your question "If the case 5 does not execute, can i do something else in that place?" is No, because it never reaches that case at all. It jumps to the next matching case or default.
Is it possible without an If/else condition. If the case 5 does not execute, can i do something else in that place?
Use a default code block as seen below. Anything that doesn't match the cases will fallback to the default one.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
How this works:
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, the default code block is executed.
A standard if/else would be the best way to achieve this. I wonder why you want to do it without.
That said, It's not very elegant, but you could try adding the following to the top of your switch statement:
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
document.write("Finally Something");
Giving you:
switch (theDay)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
document.write("Finally Something");
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
You can do something like:
var something = 0;
switch (theDay) {
case 5:
document.write("Finally Friday");
something = 15;
break;
case 6:
document.write("Super Saturday");
something = 16;
break;
case 0:
document.write("Sleepy Sunday");
something = 20;
break;
default:
document.write("I'm looking forward to this weekend!");
}
switch (something) {
case 15: document.write("Not Friday"); break;
case 16: document.write("Not Saturday"); break;
case 20: document.write("Not Sunday"); break;
default: document.write("Nothing"); break;
}
Overly complicated answers.
Simplify.
var switchElse = true;
switch (CHECK_SOMETHING)
{
case "SOME_VALUE":
...DO SOMETHING...
switchElse = false;
break;
default:
}
if (switchElse)
{
...DO ELSE...
}
The only solution that can be formulated without a compare.
USE "DEFAULT" PATTERN
var myValue = "Friday"
switch (CHECK_SOMETHING)
{
case "SOME_VALUE":
myValue = "Some Other Day";
default:
}

Why does this switch statement fail?

switch (t.value) {
case < 5:
alert('hi');
break;
}
I know it's the part where I have "< 5". How do I make it so that it has a case where t.value is less than 5??
switch only supports equality comparisons.
if (t.value < 5) {
alert('hi');
}
I don't know if it fits your particular case, but you could also do something like this:
switch (t.value) {
case 5:
case 4:
case 3:
case 2:
case 1:
alert('hi');
break;
}
An if statement seems best suited for this purpose, but although I do not recommend it the fact that JavaScript will let you switch on any datatype (and not just numbers/enums like some languages) means you can do this:
switch(true) {
case t.value < 5:
// do something
break;
case t.value >= 112:
// do something
break;
case someOtherVar == 17:
// do something
break;
case x == 7:
case y == "something":
case z == -12:
case a == b * c:
// works with fallthrough
break;
case someFunc():
// even works on a function call (someFunc() should return true/false)
break;
default:
// whatever
break;
}
The above should select whichever case matches first, noting that several if not all of the cases could be true.
In a way that style is more readable than a long series of if/else if, but I wouldn't use it in a team development environment where it could confuse other developers.
Another, more conventional use of switch for your less than 5 scenario would be as follows (assuming you know the range that t.value could possibly be):
switch(t.value) {
case 0:
case 1:
case 2:
case 3:
case 4:
// do something
break;
case 5:
// etc
}
switch statements don't support less-than or greater-than comparisons (or anything other than equals). Use:
if (t.value < 5) {
alert("hi");
}
default:
if(t.value< 5)
alert('hi');
break;
Maybe it's you want!

Categories

Resources