Memoize a Function
Memoize a Function is a reusable JavaScript snippet. Caches the results of expensive function calls based on arguments. Subsequent calls with the same arguments return the cached result. The full implementation: function memoize(fn) { const cache = new Map() return function(...args) { const key = JSON.stringify(args) if (cache.has(key)) return cache.get(key) const result = fn.apply(this, args) cache.set(key, result) return result } } // Usage const fibonacci = memoize(function(n) { if (n <= 1) return n return fibonacci(n - 1) + fibonacci(n - 2) }) fibonacci(100) // Fast due to memoization This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.