I need to dynamically add cases to a switch. I want the user to be able to add items and every item needs it\'s own switch case.
This was the best solution for my needs, but works only with a limited number of custom cases:
var cases = [false, false];
switch(condition) {
case cases[0]:
doStuff();
break;
case cases[1]:
doSomethingElse();
break;
}
Now, you can dynamically change the values in the array cases
, and the condition in the switch case will be triggered respectively;
You can click the above snippet to see it working ;)
const cases = [false, false]; // shall be defined
$('#option1').click( function() {
cases = [38,37];
});
$('#option2').click( function() {
cases = [39,40];
});
$(window).keydown( function(e) {
switch (e.keyCode) {
case 32:
$("body").append('space
');
break;
case cases[0]:
$("body").append((e.keyCode == '38' ? 'UP' : 'RIGHT' ) + '
');
break;
case cases[1]:
$("body").append((e.keyCode == '37' ? 'LEFT' : 'DOWN' ) + '
');
break;
}
});
At the begining the switch only take in account SPACE keyCode
-if you click option1 then it recognize UP and LEFT
-if you click option2, the aboves are replaced with RIGHT and DOWN
OPTION 1
OPTION 2