Solutions
To force both cases to perform process B we can list them in order with no break
statements, and then use an if
statement instead of the duplicate case
statement you used to perform the operation not required of case 1.
switch(variable) {
case 0:
case 1:
// operation B;
if(variable === 0) //operation A ;
break;
}
or alternatively nesting functions will be a good solution if process B would precede process A no matter the circumstance.
process_A = function(){
process_B();
console.log("running operation A");
//operation A;
}
process_B = function(){
console.log("running operation B");
//operation B;
}
variable = 0;
switch(variable) {
case 0:
process_A();
break;
case 1:
process_B();
break;
}
Explanation of Switch Tables and Duplicate Cases
It doesn't make sense to include duplicate cases in a switch table. Only 1 case will be indexed by variable. If you require complex relationships between conditions you probably need to use ifelse
blocks or something along the line of Rando's solution.
The following snippet demonstrates why you should never use duplicate cases in a switch table:
var variable = 0;
switch(variable) {
case 0:
console.log("case 0: No Op performed");
case 1:
// operation B;
console.log("case 1: Op B performed");
break;
case 0:
// operation A;
console.log("case 0: Op A performed");
break;
}
Notice how operation A never runs.
A switch table is similar to an array. Each case is an index of the table, which allows us to quickly handle conditions, rather than moving linearly down ifelse
blocks. When we index a switch table we perform all commands from that index to the end of the table or until the first break