Skip to content
GreenSnippets

Memoize a function

Cache results by argument so expensive pure functions only run once per distinct input.

JavaScript
function memoize(fn, getKey = (...args) => JSON.stringify(args)) {
  const cache = new Map();
  return function memoized(...args) {
    const key = getKey(...args);
    if (cache.has(key)) return cache.get(key);
    const value = fn.apply(this, args);
    cache.set(key, value);
    return value;
  };
}

Example / expected output

Output
const slowSquare = memoize((n) => n * n);
slowSquare(9); // computed
slowSquare(9); // returned from cache

How it works

Only memoize pure functions. The default key is the JSON of the arguments; pass getKey for arguments that are not serializable. The cache is unbounded, so for long-running processes add an eviction policy such as a size cap.

  • JavaScript Tested

    Run a function only once

    Wrap a function so it executes on the first call and returns the same result afterwards.

  • JavaScript Tested

    Curry a function

    Turn a multi-argument function into one that can be called a few arguments at a time.

  • JavaScript Tested

    Compose and pipe functions

    Chain single-argument functions left-to-right with pipe, or right-to-left with compose.