Memoize a function
Cache results by argument so each input is computed once.
function memoize(fn) {
const cache = new Map();
return arg => {
if (!cache.has(arg)) cache.set(arg, fn(arg));
return cache.get(arg);
};
}
Usage
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
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.
Keep exploring
- Logical xor operator — True when exactly one of two values is truthy.
- Identity function — Return the argument unchanged.
- Box handler — Chain transformations on a value, then unwrap the result.