Closures & Scopemedium
Implement memoize(fn)
Write a `memoize` function that caches the results of function calls. Subsequent calls with the same arguments should return the cached result without re-running the function.
Asked at Google, Meta, Amazon
Answer
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 function expensiveFib(n) { if (n <= 1) return n return expensiveFib(n - 1) + expensiveFib(n - 2) } const fib = memoize(expensiveFib) fib(40) // computed fib(40) // instant cache hit