Is there a way to write a conditional switch statement in javascript?
I\'m guessing not, since the following is always going to default:
var raw
Don't try this at home, or take it too seriously, this is just for sugary fun...
function conditionalSwitch(value, cond, callback /* cond, callback, cond, callback, ... */ ) {
for (var i = 1; i < arguments.length; i += 2) {
if (arguments[i](value)) {
arguments[i + 1](value);
return;
}
}
}
function test(val) {
let width, height;
conditionalSwitch(val,
(val) => val > 10,
() => [height, width] = [48,36],
(val) => val > 5,
() => [height, width] = [40, 30],
// Default
() => true,
() => [height, width] = [16, 12]
)
console.log(width, height);
}
test(4.9); // 12 16
test(5.1); // 30 40
test(10.1); // 36 48