'shorthand switch statement with conditional OR operator
Is it possible to do that? For exanple for 'a' or 'b' is equal to 'X'. If 'c' or 'd' or 'e' is equal to 'Y'
var qwerty = function() {
var month = 'a';
var cases = {
'a' || 'b' : month = 'X',
'c' || 'd' || 'e' : month = 'Y'
};
if (cases[month]) {
cases[month]();
}
return month;
};
console.log( qwerty() );
Thank you in advance :)
Solution 1:[1]
[2022 updated the answer]
Not sure what your method should return (now it simply returns 'a'). This is a possible rewrite, to demonstrate 'switching' using shortcut boolean evaluation.
With regard to @John Pace's comment/answer, I deviced a little test @Stackblitz
// original answer, simplified
const qwerty = m =>
/[ab]/.test(m) && 'X' ||
/[cde]/i.test(m) && 'Y' || 'NOPES';
// stacked switch
const qwerty1 = m => {
switch (m) {
case `a`:
case 'b':
return `X`;
case 'c':
case 'd':
case 'e':
return `Y`;
default:
return `NOPES`;
}
};
console.log(qwerty('b'));
console.log(qwerty('e'));
console.log(qwerty('x'));
console.log(qwerty1('b'));
console.log(qwerty1('e'));
console.log(qwerty1('x'));
.as-console-wrapper {
max-height: 100% !important;
}
Solution 2:[2]
There is no 'or' in a switch statement, as such. But you can stack up your cases like so:
switch(month){
case 'a':
case 'b':
month = 'X';
break;
case 'c':
case 'd':
case 'e':
month = 'Y';
break;
}
Solution 3:[3]
KooiInc's answer is very cool looking, but there is a huge issue with it. The code converts a switch to a regex. I ran a timer in Javascript on Mozilla using KooiInc's code looped 10,000,000 times and the equivalent switch statement run the same number of times. After several looped iterations, the average runtime of the switch statement was 21ms. KooiInc's regex had an average runtime of 2494ms. That is approaching 17,000% slower.
I love wild code and I really like the look of KooiInc's solution, but the overhead is just too high for practical application. The code I ran is below and the timer is at the bottom. results appear in the JavaScript console.
return{U:/[2]/.test(Units)&&(t=t*dpi)||/[3]/.test(Units)&&(t=t*dpi*2.54)||/[4]/.test(Units)&&(t=t*dpi*25.4)||t};
// ======================================
switch(Units)
{
case 2: //inches
t=t*dpi;
break;
case 3: //cm
t=t*dpi*2.54;
break;
case 4: //mm
t=t*dpi*25.4;
break;
}
return t;
// ======================================
console.time("test");
for (z=0;z<10000000;z++)
{
pU(10);
}
console.timeEnd("test");
Solution 4:[4]
You can try below code,
switch (varName)
{
case "a":
case "b":
alert('X');
break;
case "c":
case "d":
case "e":
alert('Y');
break;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | John Pace |
Solution 4 | Kishori |