javascript 29 lines · 7 steps

Building a memoize wrapper in JavaScript

A higher-order function caches results by argument so expensive calls run only once per input.

Explained by highlit
1function memoize(fn, resolver) {
2 const cache = new Map();
3 
4 function memoized(...args) {
5 const key = resolver ? resolver(...args) : JSON.stringify(args);
6 
7 if (cache.has(key)) {
8 return cache.get(key);
9 }
10 
11 const result = fn.apply(this, args);
12 cache.set(key, result);
13 return result;
14 }
15 
16 memoized.cache = cache;
17 memoized.clear = () => cache.clear();
18 
19 return memoized;
20}
21 
22const fibonacci = memoize(function fib(n) {
23 return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
24});
25 
26const distance = memoize(
27 (a, b) => Math.hypot(b.x - a.x, b.y - a.y),
28 (a, b) => `${a.x},${a.y}:${b.x},${b.y}`
29);
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A closure over a Map lets each memoized function keep its own private, persistent cache.
  2. 2A custom resolver turns non-primitive arguments into reliable cache keys where JSON.stringify falls short.
  3. 3Attaching helpers like clear onto the returned function exposes control over the cache without leaking it.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a memoize wrapper in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code