The problem this addresses is having a ridiculous amount of simple if statements in a function, cases for this may be:
The problem we're going to show this against is mapping, more implicitly, mapping a score from a slider to text.
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:
Cons:
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:
Cons:
2022-11-02 - Quick JS |
---|
Getting rid of complicated mapping functions, quickly. |
Think this would help others? |
|