Skip to main content
04

Implement memoize

EasyclosurescachingMap

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Implement memoize(func). It returns a function that does the same thing as func, but remembers the result for each argument. Calling it again with the same argument returns the stored result without calling func.

Memoization trades memory for speed: it pays off for pure functions that are slow and get called with the same input again and again.

js
let calls = 0
const square = (n) => {
  calls++
  return n * n
}
const memoizedSquare = memoize(square)

memoizedSquare(4) // 16, calls is 1
memoizedSquare(4) // 16, calls is still 1
memoizedSquare(5) // 25, calls is 2

Requirements

  • func takes a single argument, which can be any value.
  • The first call with an argument calls func and returns its result. Later calls with the same argument return that result without calling func.
  • Arguments are compared by identity: 1 and '1' are different arguments, and so are two objects with the same contents.
  • Every result is remembered, including undefined, null, 0 and false.
  • Each memoized function has its own cache.

Approach

Keep a Map from argument to result in a closure, so each memoized function gets its own private cache.

On every call:

  1. If the cache has the argument, return the stored result.
  2. Otherwise call func, store the result under the argument, and return it.

Why a Map, and why has

Two choices make the difference between a solution that works and one that almost works:

  • Map, not a plain object. Object keys are always strings, so cache[1] and cache['1'] are the same entry, and every object argument becomes '[object Object]'. A Map compares keys by identity (SameValueZero), so 1, '1' and each object get their own entry.
  • cache.has(arg), not if (cache.get(arg)). A truthiness check treats a stored 0, false, '' or undefined as a miss and calls func again every time.

Complexity

O(1) on average per call on top of func itself. Memory grows by one entry for every distinct argument, and nothing is ever removed.

Follow-ups interviewers ask

  • Several arguments: build a key from all of them, such as JSON.stringify(args) for primitives, or a tree of nested Maps (one level per argument) to keep identity semantics.
  • Custom key: accept a resolver(...args) that returns the cache key, like Lodash's memoize.
  • Memory leaks: a cache that never forgets can grow forever. Use a WeakMap for object arguments, or evict old entries with an LRU cache.
  • Async functions: cache the promise itself, so concurrent callers share one request, and remove it if it rejects.

Reference solution

js
/**
 * @param {Function} func
 * @returns {Function}
 */
export default function memoize(func) {
  const cache = new Map()

  return function memoized(arg) {
    if (cache.has(arg)) return cache.get(arg)
    const result = func(arg)
    cache.set(arg, result)
    return result
  }
}
ts
export default function memoize<Arg, Result>(func: (arg: Arg) => Result): (arg: Arg) => Result {
  const cache = new Map<Arg, Result>()

  return function memoized(arg: Arg) {
    if (cache.has(arg)) return cache.get(arg) as Result
    const result = func(arg)
    cache.set(arg, result)
    return result
  }
}