Lesson 3 of 8
Memoizing function results
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Never compute the same thing twice
Explanation
If a function is pure, meaning it always returns the same output for the same input and changes nothing outside itself, then computing it twice for the same input is wasted work.
The idea behind memoize is to wrap the function and store each result under a key that represents its inputs. If the key is already stored, you return its result; otherwise you compute the result and then store it.
A Map suits this better than a plain object, because it accepts any type as a key and doesn't inherit properties that might clash with your keys.
Warning: don't use this technique on a function that isn't pure. If it reads the time or depends on state outside itself, it will hand you a stale result.
Your task
Write memoize(fn) so the original function is never called twice for the same input.
Checks
6 checks- memoize returns a function
- The result is correct
- The same input is computed once
- A different input is computed again
- Tells multiple arguments apart
- Three calls on the page needed one computation