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.
2
Answers
Nick Parson gave this awesome idea:
Which works perfectly in this situation; So to incorporate it to example I posted and accept it as an answer:
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.
(I will accept this as an answer in 2 days, to have this question marked as answered, unless Nick will post their own answer for credit)
From my above comment …
Since the OP clearly is in control of the switch-case related code, why not implementing each case specific handling as own function. Thus, firstly decoupling the implementation of the case specific handling from the
mySwitch
function (the one of the OP’s own answer) and secondly enabling code-reuse for the OP’s example code’s 3rd case.The next provided example code in my eyes is much easier to comprehend than what the OP did come up with in his own answer …
… and in case the switch value is clearly either string or number based, one could shorten the above
mySwitch
function to …