Memoize a function

Cache results by argument so each input is computed once.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

memoize-a-function.js
function memoize(fn) {
  const cache = new Map();
  return arg => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}

Usage

usage.js
let calls = 0;
const isEven = memoize(n => (calls += 1, n % 2 === 0));
[isEven(3), isEven(3), isEven(3)]; // → [false, false, false]
calls; // → 1
const fibonacci = memoize(n => (n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2)));
fibonacci(50); // → 12586269025

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

Know the limits

  • The original cached with cache[arg] || …, so falsy results (0, "", false) were recomputed on every call: three calls above would have run three times. A Map also keeps 1 and "1" apart.
  • One argument, compared with SameValueZero: two equal-looking objects are different keys.
  • The cache never shrinks. In a long-running server, bound it (an LRU) or key it by a finite set.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Memoize a function from the original 1loc collection by Nguyen Huu Phuoc, with Kikobeats. Copyright (c) 2020 phuoc-ng. MIT licensed.

Caches in a Map with has(); the original recomputed falsy results on every call and merged 1 and "1". Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.