When working with a switch case, the default case handles any scenarios that are not covered by the expected cases. To simplify my code and reduce cyclomatic complexity, I ended up replacing the switch case with an object literal function.
function test(){
const options = getOptions();
switch(options){
case 'a':
return 'foo';
case 'b'
return 'bar';
default:
return 'Nothing';
}
}
The new function I created:
function test(){
const options = getOptions();
return {
'a': 'foo',
'b': 'bar',
'': 'Nothing',
null: 'Nothing',
undefined: 'Nothing'
}[options]
}
test();
One concern was that any input other than 'a' or 'b' would result in undefined, unlike the switch case which could handle all other scenarios in the default case.
I attempted to address this issue using a regular expression like so:
function test(){
const options = getOptions();
const nonValidInput = new RegExp([^c-zC-Z], 'g');
return {
'a': 'foo',
'b': 'bar',
'': 'Nothing',
null: 'Nothing',
undefined: 'Nothing',
nonValidInput: 'Nothing'
}[options]
}
However, the scope of the above regular expression is not recognized inside the return statement, and the default case is not functioning as intended. Any suggestions on how to handle the default case effectively?