Search code examples
javascriptobjectecmascript-6object-literal

Need an equivalent of the default of switch case in an object literal function


In a switch case, default would be anything but the expected cases. I had to replace my switch case with a object literal function to reduce the cyclomatic complexity.

function test(){
  const options = getOptions();
  switch(options){
   case 'a':
       return 'foo';
   case 'b'
       return 'bar';
   default:
       return 'Nothing';
  }
}

The replacement function I wrote:

function test(){
  const options = getOptions();
   return {
      'a': 'foo',
      'b': 'bar',
      '': 'Nothing',
      null: 'Nothing',
      undefined: 'Nothing'
   }[options]
}

test();

The concern is any alphabet other than a,b would return undefined unlike switch case that would handle all other options in default.

I tried this:

function test(){
  const options = getOptions();
  const default = new RegExp([^c-zC-Z], 'g');
   return {
      'a': 'foo',
      'b': 'bar',
      '': 'Nothing',
      null: 'Nothing',
      undefined: 'Nothing',
      default: 'Nothing'
   }[options]
}

The above regular expression addresses my concern of covering all other than 'a','b' but the scope is not there inside the return statement, default is not recognized. Please suggest on the default case.


Solution

  • You could try this approach

    function test(){
      const result = {
          'a': 'foo',
          'b': 'bar'
       }[getOptions()];
      return result ? result : 'Nothing';
    }
    
    test();