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
Top comments (5)
So what is the benefits of using a lookup table other than it looks much cleaner?
From the 1st link in the resources section:
Why is this referred to as a lookup table, when it's just a plain old object with values retrieved by keys like with any object?
You are right, that from a syntactic point of view, this is a plain old object. A pattern, like the lookup table pattern, is a reusable solution to a commonly occurring problem.
The problem, in this case, is how to express a set of exclusive choices so that the code goes directly to the right choice, without evaluating any of the irrelevant choices, making the code shorter, clearer, and more efficient. What makes this object a 'lookup table' is not its syntax, but the purpose to which it is being put (its pragmatics).
Other plain old objects may have very different purposes. Every pattern must use some ordinary js syntactic structures, otherwise, they could not execute. The pattern is not about 'what' but about 'why'.
This is a great article. I wasn't aware of the advantages of this pattern, and more so, I'd not used Record in typescript before so this was extra informative