06

Memoize with custom key

15 min·senior·

Implement memoize(fn, keyFn?) returning a memoized version of fn. Default key = first argument. keyFn (optional) takes (...args) and returns a primitive cache key.

const slow = (n) => { /* heavy */ return n * n; };
const fast = memoize(slow);
fast(4); // computes
fast(4); // cached

Add a .clear() method.

expected time · O(1) per call after warm
expected space · O(unique keys)
4 lines
⏵ run · no run yet · ctrl+enter