Skip to content
jshacks.dev
Functions

Memoize a function with a Map

Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.

1 min read
Summarize in AI

A pure function with the same input always gives the same output, so computing it twice is waste. Keep each result in a Map and return it on the next call.

JavaScript
const memoize = (fn) => {
  const cache = new Map();
  return (arg) => {
    if (cache.has(arg)) return cache.get(arg);
    const value = fn(arg);
    cache.set(arg, value);
    return value;
  };
};

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

square(4);
square(4);
square(5);
console.log(calls, square(4));
Text
2 16

cache.has is used instead of testing the value, so a result of undefined or 0 is cached rather than recomputed. A Map accepts any value as a key, with NaN equal to NaN.

It only works for one argument and a pure function. For several arguments, build a key with JSON.stringify(args), which is slower and breaks on values JSON cannot represent. The cache also never shrinks, so see the snippet on clearing memoization caches before using it on unbounded input.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.