This is very similar to default as first option in switch statement? , but regarding JS rather than PHP.
I have a helper function that wraps various calling styles for another function. The wrapped function requires at least one, and can accept up to 4 parameters. What I am doing is fairly well described by this minimum code example, which works fine in my versions of Chrome and FF.
function testSwitch(definition) {
var term, minLength, boundaryStart, boundaryEnd;
switch (definition.length) {
default:
case 4:
boundaryEnd = definition[3];
case 3:
boundaryStart = definition[2];
case 2:
minLength = definition[1];
case 1:
term = definition[0];
break;
case 0:
console.log('fail')
return;
}
console.log(term, minLength, boundaryStart, boundaryEnd);
}
(In the real use case they are passed to the actual function rather than console.log). So the idea is to fall through the cases, allowing too many parameters to be provided (but ignoring the extra ones), but failing if the definition provided is empty.
So I know from my testing that this appears to work in some browsers at least, can I rely on this working across reasonably recent browsers (eg iOS/Android devices, IE8+, Edge etc)? I know that excluding the break statement is well-defined behavior and used fairly broadly, but am not so sure about having the default case first and empty (eg. if some browsers JS engines would optimize out the empty default case then this doesn't work for me, as it would not work when called with an array of size 5, for example).
I've never seen someone use this approach before. It's clever. As a side note, clever is a two-edged blade; if this is code that anyone other than you will be touching, I strongly suggest a comment there to make it clear you did that on purpose or someone is going to alter it (because it 'looks wrong') and break it without realizing the intent.
The documentation indicates that default
is not required to be the last clause.
If you find a browser were it does NOT work, you could modify it slightly thus and avoid the default
:
function testSwitch(definition) {
var term, minLength, boundaryStart, boundaryEnd;
switch (definition.length > 4 ? 5 : definition.length) {
case 5:
case 4:
boundaryEnd = definition[3];
case 3:
boundaryStart = definition[2];
case 2:
minLength = definition[1];
case 1:
term = definition[0];
break;
case 0:
console.log('fail')
return;
}
console.log(term, minLength, boundaryStart, boundaryEnd);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With