{name:"craig",surname:"white"}

Learn javascript lookup tables in 3 mins

Problem

The problem this addresses is having a ridiculous amount of simple if statements in a function, cases for this may be:

  • Mapping
  • Validation
  • Navigation

The problem we're going to show this against is mapping, more implicitly, mapping a score from a slider to text.

Naive approach

const mapValueToDefinition = (value: number) => { if (value === 1) { return 'low'; } if (value === 2) { return 'needing work'; } if (value === 3) { return 'getting there'; } if (value === 4) { return 'doing good'; } if (value === 5) { return 'great'; } } // Usage <span>You said your score is {value.toString()} ({mapValueToDefinition(value)})</span>

Pros:

  • People are generally used to functions being used so immediately understandable
  • Can be easily changed to use > or <

Cons:

  • Unnecessarily complicated
  • Quite messy

Refactor

Introducing lookup tables, the conditions become the keys, and the results become the values.

const valueToDefintionMap = { 1: 'low', 2: 'needing work', 3: 'getting there', 4: 'doing good', 5: 'great' } // Usage: <span>You said your score is {value.toString()} ({valueToDefinitionMap[value]})</span>

So if you passed in 1, it results in 'low', and if you passed in 4 it results in 'doing good'.

Pros:

  • More readable
  • Simple
  • Easy to add more cases

Cons:

  • Tricky to change if needing > or < operations
2022-11-02 - Quick JS
Getting rid of complicated mapping functions, quickly.
Think this would help others?