So it is possible to fall-through the case to another case:
switch(variable) {
case 1:
// do something 1
case 2:
// do something 2
break;
case 3:
// do something 3
break;
}
But what if we would want to execute multiple other cases after finishing the main case, or execute other case that is not directly after the main case?
Pseudocode for example:
switch(variable) {
case 1:
// do something 1
break;
case 2:
// do something 2
break;
case 3:
// do something 3
execute case 2;
execute case 1;
break;
}
I've researched the option of labeled statements, but it's not gonna work here it seems.
The only option I see here is to create new function for every case, but I'm wondering - is there better, cleaner, more readable and/or shorter option?
I'm looking for all tips - be it some keyword I'm missing, your personal tips to do it cleanly, or libraries and even propositions from other languages like typescript etc.
Nick Parson gave this awesome idea:
Maybe wrap the whole switch in a function that accepts variable and do a recursive call?
Which works perfectly in this situation; So to incorporate it to example I posted and accept it as an answer:
mySwitch(variable);
function mySwitch(_v) {
switch(_v) {
case 1:
// do something 1
break;
case 2:
// do something 2
break;
case 3:
// do something 3
mySwitch(2);
mySwitch(1);
break;
}
}
It's clean, does the trick... and moreover - if you declare function where switch statement normally would be (in example inside some outer function), you will be able to change variables declared in the outer function, just like you would be able to inside switch statement.