JavaScript Snippet

Memoize Higher-Order Function

Difficulty: Medium

Memoization caches function results keyed by arguments so repeat calls return in O(1). This snippet covers the canonical single-arg memoize, a multi-arg version that handles object identity via a `Map` chain, and an LRU-bounded variant that prevents unbounded cache growth. Use it for pure functions whose work dwarfs the lookup cost (parsing, layout calc, recursive DP).

Code Snippets
/

Memoize Higher-Order Function

Memoize Higher-Order Function

Memoization caches function results keyed by arguments so repeat calls return in O(1). This snippet covers the canonical single-arg memoize, a multi-arg version that handles object identity via a `Map` chain, and an LRU-bounded variant that prevents unbounded cache growth. Use it for pure functions whose work dwarfs the lookup cost (parsing, layout calc, recursive DP).

JavaScript
Medium
3 snippets
utility
code-template
memoization
higher-order-functions

458 views

7

When the function takes one primitive argument (number, string, boolean), a plain Map is the cleanest cache: O(1) lookup, structural equality on keys, and no JSON.stringify overhead. Memoizing a recursive function flips a naive O(2^n) Fibonacci to O(n) by sharing sub-results, which is why DP problems get a speed-up just by adding this wrapper. The body must recurse through fib (the memoized binding) rather than a self-referencing inner name, otherwise the recursion bypasses the cache. Use this version any time the input space is small and primitive.