This might be a short discussion. Is there a reason not to add/allow a regex as a value for a case in a swtich?
function doStuff(arg) {
switch (arg) {
case /abc/:
// do something
break; // or return
case /xyz/:
// do something else
break; // or return
// other cases with other regexs
default:
// do other things
break; // or return
}
}
doStuff('abc'); // matches /abc/
doStuff('xyz'); // matches /xyz/
doStuff(undefined); // matches default (maybe)
It has been valid syntax since ES3, though it's useless (because case /xyz/: never matches). We can't change the semantics (theoretically possible, but very unlikely in practice). So the only option is to introduce a new feature, aka. the pattern matching proposal.
I guess I was a little unclear. I was intending to ask about why we wouldn't want to add it as a feature in a future version. Secondly, my intention was for it to work by actually testing the pattern against the value provided in the switch(value) opening statement. So it would behave more like this:
function doStuff(arg = '') {
switch (true) {
case /abc/.test(arg):
return 'hello'
case /xyz/.test(arg):
return 'world';
// other cases with other regexs
default:
// do other things
return 'nope.'
}
}
doStuff('abc'); // matches /abc/
doStuff('xyz'); // matches /xyz/
doStuff(undefined); // matches default (maybe)