loading...

Use lookup tables for cleaning up your JS/TS code

k_penguin_sato profile image K-Sato Updated on ・1 min read

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

Resources

Posted on by:

k_penguin_sato profile

K-Sato

@k_penguin_sato

I am a software-engineer based somewhere on earth.

Discussion

markdown guide
 

So what is the benefits of using a lookup table other than it looks much cleaner?

 

From the 1st link in the resources section:

  • Eliminate the branching by the if-else ladder and make the rule engine a simple O(1) lookup
  • Default evaluation does not need to wait for all conditions to get processed. If a key does not exist in the lookup table, it returns the default condition straightaway
 

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

 

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?