Sub topic 14
Caching Results with Memoization
This chapter assumes you are comfortable with closures that hold private state, which the previous chapters covered. It also assumes you know Map, rest parameters (...args), and Function.prototype.apply. Memoization is the first pattern here where the closure's private variable does real work. That variable is a cache that makes repeated calls cheap.
What Memoization Is
Memoization means storing the result of a function call, keyed by its arguments. When the same arguments arrive again, the stored result is returned and the work is skipped. A closure fits this job because the cache has to meet two conditions:
- It must persist between calls. A local variable inside the function body would be recreated on every call.
- It should be hidden from callers. A global cache can be overwritten or cleared by any code.
A variable that lives in the outer function and is used by the returned inner function meets both conditions.
function memoize(fn) {
const cache = new Map();
return function (n) {
if (cache.has(n)) {
return cache.get(n);
}
const result = fn(n);
cache.set(n, result);
return result;
};
}
const square = memoize((n) => n * n);
console.log(square(4)); // 16, computed
console.log(square(4)); // 16, read from cacheEach call to memoize creates a new cache. If you memoize two different functions, they never share entries.
Why `has` and Not a Truthiness Check
A common shortcut is if (cache.get(n)) return cache.get(n);. This breaks whenever the real result is falsy, such as 0, '', false, null, or undefined. In those cases the function recomputes every time, so you pay the cost and get no benefit. cache.has(n) tells "never computed" apart from "computed, and the answer was falsy".
Map compares keys with SameValueZero. That means NaN matches NaN and 0 matches -0. A plain object used as a cache would turn every key into a string, so 1 and '1' would collide. This is one reason to prefer Map.
Memoizing Recursive Functions
Memoization pays off most with recursive functions that solve the same subproblem many times. Fibonacci is the standard example. It also shows the most common memoization mistake.
function memoize(fn) {
const cache = new Map();
return function (n) {
if (cache.has(n)) return cache.get(n);
const result = fn(n);
cache.set(n, result);
return result;
};
}
let slowCalls = 0;
const slowFib = (n) => {
slowCalls += 1;
return n < 2 ? n : slowFib(n - 1) + slowFib(n - 2);
};
// Mistake: wraps the outside, but the recursion still calls slowFib.
const wrongFib = memoize(slowFib);
slowCalls = 0;
wrongFib(20);
console.log('wrapped from outside:', slowCalls); // 21891
// Correct: the recursive calls go through the memoized function.
let fastCalls = 0;
const fib = memoize((n) => {
fastCalls += 1;
return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
fib(20);
console.log('memoized recursion:', fastCalls); // 21
console.log(fib(50)); // 12586269025wrongFib caches only the top-level answer. Inside, slowFib refers to itself by name, and that name resolves through the scope chain to the unmemoized function. The correct version works because the arrow function refers to fib, a const in the enclosing scope. By the time the arrow function first runs, fib already holds the memoized wrapper. This is capture by reference: the arrow function reads fib when it runs, not when it is created.
Multiple Arguments and Cache Keys
The simple version uses only the first argument as the key. If you pass it a two-argument function, it silently returns wrong answers: add(1, 2) and add(1, 5) would share the key 1. You need a way to turn all the arguments into one key. A common design accepts a resolver, a function that builds the key. Lodash's memoize uses the same design.
function memoize(fn, resolver = (...args) => args[0]) {
const cache = new Map();
function memoized(...args) {
const key = resolver(...args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
}
memoized.clear = () => cache.clear();
return memoized;
}
const add = memoize(
(a, b) => a + b,
(a, b) => `${a}|${b}`
);
console.log(add(1, 2)); // 3
console.log(add(1, 5)); // 6
add.clear(); // empties the private cacheThis version adds two more details. fn.apply(this, args) passes the caller's this through, so the wrapper still works as an object method. memoized.clear is a second closure over the same cache. It gives callers a controlled way to reset the cache without exposing the cache itself.
Key strategies and their failure modes
| Strategy | Works for | Fails when | Column |
|---|---|---|---|
| First argument as key | One primitive argument | Any extra argument changes the result | |
| Template string such as `${a}\ | ${b}` | A known, small set of primitives | Values contain the separator, or `1` and `'1'` must be treated as different |
| `JSON.stringify(args)` | Plain data | Key order differs, values are functions, `undefined`, or `NaN` (all lost or changed), or arguments are cyclic objects (throws) | |
| Object reference (Map or WeakMap) | Immutable objects | The object is mutated after being cached, so the stored result is stale |
Object Arguments and WeakMap
When the argument is an object, a Map keys on its identity. Two objects with identical contents are different keys. The same object, even after you mutate it, is the same key. A Map also keeps every key object alive for as long as the cache exists.
A WeakMap holds its keys weakly. Once nothing else references a key object, the garbage collector can remove both the object and its cache entry.
function memoizeByObject(fn) {
const cache = new WeakMap();
return function (obj) {
if (cache.has(obj)) return cache.get(obj);
const result = fn(obj);
cache.set(obj, result);
return result;
};
}
const totalOf = memoizeByObject((order) =>
order.items.reduce((sum, item) => sum + item.price, 0)
);
const order = { items: [{ price: 10 }, { price: 15 }] };
console.log(totalOf(order)); // 25
order.items.push({ price: 5 });
console.log(totalOf(order)); // 25, stale: same reference, so cachedBounding the Cache
An unbounded cache grows with every new key. In a long-running server, it can grow until memory runs out. A small least-recently-used (LRU) cache takes advantage of the fact that a Map iterates its keys in insertion order. Deleting a key and setting it again moves it to the end. The first key is then always the least recently used.
function memoizeLRU(fn, limit = 100) {
const cache = new Map();
return function (key) {
if (cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value); // mark as most recently used
return value;
}
const value = fn(key);
cache.set(key, value);
if (cache.size > limit) {
cache.delete(cache.keys().next().value); // evict oldest
}
return value;
};
}
const slowDouble = memoizeLRU((n) => n * 2, 2);
slowDouble(1);
slowDouble(2);
slowDouble(3); // evicts key 1
console.log(slowDouble(2)); // 4, still cachedMemoizing Async Functions
For a function that returns a promise, cache the promise instead of the resolved value. Concurrent callers then share one in-flight request instead of each starting a new one. If the promise rejects, remove its entry so a later call can try again. Otherwise the cache would keep handing out the failure.
function memoizeAsync(fn) {
const cache = new Map();
return function (key) {
if (cache.has(key)) return cache.get(key);
const promise = fn(key).catch((err) => {
cache.delete(key);
throw err;
});
cache.set(key, promise);
return promise;
};
}
let requests = 0;
const fetchUser = memoizeAsync(async (id) => {
requests += 1;
return { id, name: `user${id}` };
});
Promise.all([fetchUser(1), fetchUser(1)]).then(([a, b]) => {
console.log(a === b, requests); // true 1
});When Memoization Is Worth It
| Situation | Memoize? |
|---|---|
| Expensive pure computation, repeated inputs | Yes |
| Recursion with overlapping subproblems | Yes, and route the recursion through the wrapper |
| Cheap function such as `n * n` | No. The key building and lookup cost more than the work |
| Inputs rarely repeat | No. The cache only grows |
| Impure or time-dependent function | No |
Exercise
A teammate writes const fastFact = memoize(fact), where function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); }. Calling fastFact(100) once and then fastFact(101) does not reuse the work from the first call. Why, and how do you fix it?
Show answer
The recursive call inside fact resolves the name fact through the scope chain to the original function, not to the wrapper. Only the top-level result for 100 is cached. Fix it by making the recursion call the memoized function: const fastFact = memoize((n) => (n <= 1 ? 1 : n * fastFact(n - 1)));.
Exercise
A memoized function uses if (cache.get(key)) return cache.get(key);. It wraps isEven = (n) => n % 2 === 0. What happens with isEven(3) called many times?
Show answer
The result false is stored, but cache.get(3) is falsy, so the check fails and the function recomputes on every call. Use cache.has(key) to tell "missing" apart from "stored but falsy".
Exercise
You memoize area(rect) with the resolver JSON.stringify. Two calls pass { w: 2, h: 3 } and { h: 3, w: 2 }. Do they share a cache entry? And what happens if a rectangle object is mutated after its first call when you key on the object with a WeakMap instead?
Show answer
They do not share an entry. JSON.stringify keeps property order, so the strings differ and the area is computed twice (correctly, but with no cache hit). With a WeakMap keyed on the object, the mutated rectangle is still the same reference, so the stale cached area is returned.