Memoization and cache-key design
Quick answer
Memoization caches the result of a calculation for a key so repeated equivalent requests can reuse it. Correctness depends on key design and assumptions about the calculation.
How it works
For a deterministic unary function, a Map can store results by input. Check has rather than result truthiness so cached zero, false and undefined work. Map uses identity for object keys; mutation of a key object can make a cached result stale. Multi-argument functions require an unambiguous key strategy. Bound or evict caches to control memory; do not memoize time-dependent or effectful operations indiscriminately.
let calls=0;const cache=new Map();function square(n){if(!cache.has(n)){calls++;cache.set(n,n*n);}return cache.get(n);}console.log(square(0),square(0),calls);Expected output in Node.js:
0 0 1A zero result is a valid cache hit.
const cache=new Map(),a={n:2};cache.set(a,4);a.n=3;console.log(cache.get(a),cache.has({n:3}));Expected output in Node.js:
4 falseIdentity is unchanged while the cached calculation may become stale.
Common mistakes
Do not use a truthiness check to detect a cache hit. Do not claim JSON.stringify is a universally safe structural key: unsupported values, cycles and ordering can matter.
Practice
Implement a unary memoizer and count actual calculations for repeated zero and nonzero inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memoization and cache-key design — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Why check cache.has(key) instead of Boolean(cache.get(key))?
What is a risk of an unbounded Map memoization cache?
Does Map compare object keys structurally?
What is the exact console output in Memoization and cache-key design example 1?
let calls=0;const cache=new Map();function square(n){if(!cache.has(n)){calls++;cache.set(n,n*n);}return cache.get(n);}console.log(square(0),square(0),calls);What is the exact console output in Memoization and cache-key design example 2?
const cache=new Map(),a={n:2};cache.set(a,4);a.n=3;console.log(cache.get(a),cache.has({n:3}));