Skip to the content

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 Map in 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 own getKey for special cases.
  • We use cache.has(key), not if (cache.get(key)), so results that are 0, "" or undefined are still treated as cached.

Test it

let runs = 0;
const square = memoize((x) => {
  runs++;
  return x * x;
});
square(4);     16
square(4);     16
runs           1

Memoized 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, instantly

The 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

ProblemExample
Different objects with the same contents get the same keyUsually fine for pure functions
Property order changes the key{a:1,b:2} and {b:2,a:1} give different keys
Some values are lostundefined becomes null; functions disappear
Slow for large argumentsStringifying a big object on every call
Fails on BigInt and circular objectsThrows 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 WeakMap for object keys.

Where memoization appears

  • useMemo, useCallback and React.memo in 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 of cache.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

WordMeaning
MemoizationCaching a function's results by its inputs
CacheStored results for quick reuse
Cache keyThe value used to look up a saved result
Cache hit / missFound in the cache / not found
TTLTime to live: how long an entry stays valid
Memory leakMemory that keeps growing and is never released

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.