Memoize
MediumP1Coding
Implement memoize(fn).
It returns a function that caches results. If it is called again with the same arguments, return the cached result without calling fn again.
Two calls have the same arguments when they pass the same number of arguments and each pair is the same value by ===. Cache undefined and other falsy results too. this must be forwarded to fn.
The returned function has a cache property that is the underlying Map.
Example 1
- Input
- const f = memoize(slowSquare); f(4); f(4);
- Output
- slowSquare runs once
- Why
- The second call is served from the cache.
Constraints
- Arguments are primitives or object references.
- Argument order matters: f(1, 2) and f(2, 1) are different calls.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.