Aldren Terante Aldren Terante - 10 months ago 84
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 Source

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'