Basic memoization caches a function's result by its first argument. This version adds the two things real memoizers need: a custom key resolver, so you can cache on several arguments, and cache controls — clear() and delete(key) — so stale entries can be evicted. It mirrors lodash's memoize, whose .cache is a public Map.
Implement memoize(fn, resolver). Cache fn's result per key (the first argument by default, or resolver(...args) when given). Expose memoized.cache (a Map), memoized.clear(), and memoized.delete(key).
function memoize(fn, resolver) {
// returns a memoized fn with .cache (Map), .clear(), .delete(key)
}
const add = memoize((a, b) => a + b, (a, b) => `${a},${b}`);
add(1, 2); // computes 3
add(1, 2); // cached
add(1, 3); // computes 4 (different key)
const f = memoize((n) => n * 2);
f(5); // 10, cached under key 5
f.cache.get(5); // 10
f.delete(5); // evict that entry
f.clear(); // empty the whole cache
memoize(fn) caches by args[0].resolver(...args) returns the cache key, so you can key on all arguments (e.g. `${a},${b}`).Map — exposed as memoized.cache; use a Map, not a plain object, so keys keep their type and falsy results cache correctly.clear() / delete(key) — empty the whole cache, or evict one entry (delete returns whether the key existed).0, '', and undefined must be cached, not recomputed. Check presence, not truthiness.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.