Search code examples
javascripttypescriptfunctional-programming

Better (Functional) alternate to multiple switch cases in JS


The Object Lookup method is very popular in JS and used as a better replacement for Switch-case statements e.g.

function phoneticLookup(val) {
  var result = "";

  switch(val) {
    case "alpha":
      result = "Adams";
      break;
    case "bravo":
      result = "Boston";
      break;
    case "charlie":
      result = "Chicago";
      break;
  }
  return result;
}


function phoneticLookup(val) {
  var result = "";

  var lookup = {
    "alpha": "Adams",
    "bravo": "Boston",
    "charlie": "Chicago",
  };

  result = lookup[val];
  return result;
}

But if the switch case is like the one below, as you can see multiple cases return the same result. How can we write it in a better way using objects, map, or any other way (not using if-else) in JS?

let continent = '';
switch (country) {
   case "China":
   case "India":
   case "Nepal": 
       continent = 'Asia';
       break;
   case "UK":
   case "France":
   case "Poland": 
       continent = 'Europe';
       break;
   case "Egypt":
   case "Zimbave":
   case "Somalia": 
       continent = 'Africa';
       break;
   default: 
       continent = 'Other'
       break;
}

Solution

  • I would suggest not introducing any abstraction. You can probably make your switch functional by just hiding it within a function (no need to look at a function internals)...

    The only advise on top of what you already have could be to using return rather than mutating a var and then breaking.

    const whichContinent = (country) => {
      switch (country) {
       case "China":
       case "India":
       case "Nepal": 
         return 'Asia';
    
       case "UK":
       case "France":
       case "Poland": 
         return 'Europe';
    
       case "Egypt":
       case "Zimbave":
       case "Somalia": 
         return 'Africa';
    
       default: 
         return 'Unknown'
      }
    }
    
    console.log(
      whichContinent('hogwarts'),
    );