Aldren Terante Aldren Terante - 2 months ago 24
Javascript Question

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 :)

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:

var qwerty = function(month) {
  return { month: /[ab]/.test(month) && 'X' || 
                  /[cde]/i.test(month) && 'Y' || 
                  'NOPES'};
};
qwerty('b').month; //=> 'X'
qwerty('x').month; //=> 'NOPES'