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;
}
CodePudding user response:
You have a few options. The pattern matching propsal is Stage 1 and may never make it into the standard. You could write a custom switch/match function as in this answer. For this specific case you actually could use an object lookup, just a little differently:
const continents = {
"Africa": ["Egypt", "Ghana"], // etc
"Asia": ["China", "Bhutan"], // etc
}
const assignContinent = (country) => {
const possibleMatch = Object.entries(continents)
.find((continent) => continent[1].includes(country))
return possibleMatch ? possibleMatch[0] : "Other"
}
CodePudding user response:
For performance I recommend defining a mapping with repetition of continent:
countryToContinentMap = {
China: 'Asia',
India: 'Asia',
Nepal: 'Asia',
UK: 'Europe',
France: 'Europe',
Poland: 'Europe',
Egypt: 'Africa',
Zimbave: 'Africa',
Somalia: 'Africa'
}
function getContinent(country) {
return countryToContinentMap[country] || 'Other';
}
console.log('Nepal => ' getContinent('Nepal'));
console.log('Xomur => ' getContinent('Xomur'));
Output:
Nepal => Asia
Xomur => Other
To make it easier o define the mapping, you could do it as @Zac Anger did, then programmatically reverse the mapping once before use.