Overview
You might use the if
of switch
statement like the code below when the output of your function is dependent on the given value.
Using the If statement
const colorMapper = (color) => {
if (color == "yellow") {
return "amarillo";
} else if (color == "blue") {
return "azul";
} else if (color == "red") {
return "rojo";
} else {
return "No aplica";
}
};
colorMapper("yellow"); //=> amarillo
colorMapper("pink"); //=> No aplica
Using the switch statement
const colorMapper = (color) => {
switch (color) {
case "yellow":
return "amarillo";
case "blue":
return "azul";
case "red":
return "rojo";
default:
return "No aplica";
}
};
colorMapper("yellow"); //=> amarillo
colorMapper("pink"); //=> No aplica
Using lookup tables
You can achieve the same result by creating a lookup table like the code below.
As you can see, the code is cleaner and much easier to read!
const colorsTable = {
yellow: "amarillo",
blue: "azul",
red: "rojo",
};
const colorMapper = (color) => colorsTable[color] || "No aplica";
colorMapper("yellow"); //=> amarillo
colorMapper("pink"); //=> No aplica
If you wanna use the lookup table in TypeScript, you can give types to the lookup table like below.
type ColorEn = "yellow" | "blue" | "red";
type ColorEs = "amarillo" | "azule" | "rojo";
const colorsTable: Record<ColorEn, ColorEs> = {
yellow: "amarillo",
blue: "azule",
red: "rojo",
};
const colorMapper = (color: ColorEn): ColorEs | "No aplica" => colorsTable[color] || "No aplica";
colorMapper("yellow"); //=> amarillo
colorMapper("pink"); //=> No aplica
So what is the benefits of using a lookup table other than it looks much cleaner?