JS Machine Coding Questions — Implementations You Must Know
Memoize
- Cache the result of a pure function so repeated calls with the same arguments skip recomputation.
- Key insight: Use a Map keyed by JSON.stringify(args). Works best for pure functions with primitive arguments.
- Gotcha: JSON.stringify fails for functions, undefined, circular refs — use a custom key for complex args.
- Gotcha: Each memoized function gets its own independent cache.
- Gotcha: Not useful for functions with side effects.
1function memoize(fn) {
2 const cache = new Map();
3 return function (...args) {
4 const key = JSON.stringify(args);
5 if (cache.has(key)) return cache.get(key);
6 const result = fn.apply(this, args);
7 cache.set(key, result);
8 return result;
9 };
10}
11
12const factorial = memoize(function f(n) {
13 return n <= 1 ? 1 : n * f(n - 1);
14});
15factorial(5); // computed → 120
16factorial(5); // from cache → 120