Lesson 79 of 296
memoize
On this page
The task
"Write memoize(fn) that caches results so calling it again with the same arguments returns the saved result instead of recalculating."
What memoization is
Memoization means remembering the results of a function for each input. The first call with some input does the work and saves the result. Later calls with the same input return the saved result instantly.
It only makes sense for pure functions (Lesson 38): same input, same output, no side effects.
What the interviewer is checking
- A cache in a closure.
- Choosing a cache key for several arguments.
- Map vs object (Lesson 64).
- Trade-offs: memory use and when caching is wrong.
Questions to ask first
- "How many arguments, and what types? Numbers and strings only, or objects too?"
- "Is there a limit on cache size?"
The solution
function memoize(fn, getKey = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function (...args) {
const key = getKey(...args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}- The cache is a
Mapin the closure, private to this memoized function. - The key:
JSON.stringify(args)turns arguments like(2, 3)into the string"[2,3]". A caller can pass their owngetKeyfor special cases. - We use
cache.has(key), notif (cache.get(key)), so results that are0,""orundefinedare still treated as cached.
Test it
let runs = 0;
const square = memoize((x) => {
runs++;
return x * x;
});
square(4); 16
square(4); 16
runs 1Memoized recursion: Fibonacci
Without memoization, recursive Fibonacci repeats the same work again and again and becomes extremely slow (exponential time).
const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
fib(50); 12586269025, instantlyThe recursive calls go through the memoized fib, so each value is calculated only once. This is the core idea of dynamic programming (Part 10).
Problems with JSON.stringify keys
| Problem | Example |
|---|---|
| Different objects with the same contents get the same key | Usually fine for pure functions |
| Property order changes the key | {a:1,b:2} and {b:2,a:1} give different keys |
| Some values are lost | undefined becomes null; functions disappear |
| Slow for large arguments | Stringifying a big object on every call |
| Fails on BigInt and circular objects | Throws an error |
Alternative for one object argument: use the object itself as the key in a WeakMap. Lookups are by reference and the cache does not keep the object alive.
Memoizing async functions
Cache the promise, not the result. Then two calls made at the same time share one request. If it fails, remove it so the next call can retry:
function memoizeAsync(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const promise = fn(...args).catch((error) => {
cache.delete(key);
throw error;
});
cache.set(key, promise);
return promise;
};
}Limiting memory
A cache that grows forever is a memory leak. Options:
- A maximum size with LRU removal (Lesson 83).
- A time to live (TTL): entries expire after some time.
- A
WeakMapfor object keys.
Where memoization appears
useMemo,useCallbackandReact.memoin React (Part 12).- Selectors in state libraries.
- Expensive calculations: formatting, parsing, maths.
Common mistakes
- Memoizing impure functions (for example, ones that read the current time or a database).
if (cache.get(key))instead ofcache.has(key).- A cache with no limit on a long-running server.
- Recursive functions that call the original, not the memoized version.
How to say it in an interview
"memoize returns a wrapper with a private Map cache in its closure. It builds a key from the arguments, by default with JSON.stringify, returns the cached value if the key exists using has rather than a truthy check, and otherwise calls the function and stores the result. It only suits pure functions. For async functions I cache the promise so concurrent calls share it, and remove it on failure. In production I would bound the cache with LRU eviction or a TTL to avoid memory leaks."
Key words
| Word | Meaning |
|---|---|
| Memoization | Caching a function's results by its inputs |
| Cache | Stored results for quick reuse |
| Cache key | The value used to look up a saved result |
| Cache hit / miss | Found in the cache / not found |
| TTL | Time to live: how long an entry stays valid |
| Memory leak | Memory that keeps growing and is never released |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.