Implement memoize
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement memoize(func). It returns a function that does the same thing as func, but remembers the result for each argument. Calling it again with the same argument returns the stored result without calling func.
Memoization trades memory for speed: it pays off for pure functions that are slow and get called with the same input again and again.
let calls = 0
const square = (n) => {
calls++
return n * n
}
const memoizedSquare = memoize(square)
memoizedSquare(4) // 16, calls is 1
memoizedSquare(4) // 16, calls is still 1
memoizedSquare(5) // 25, calls is 2Requirements
functakes a single argument, which can be any value.- The first call with an argument calls
funcand returns its result. Later calls with the same argument return that result without callingfunc. - Arguments are compared by identity:
1and'1'are different arguments, and so are two objects with the same contents. - Every result is remembered, including
undefined,null,0andfalse. - Each memoized function has its own cache.
Approach
Keep a Map from argument to result in a closure, so each memoized function gets its own private cache.
On every call:
- If the cache has the argument, return the stored result.
- Otherwise call
func, store the result under the argument, and return it.
Why a Map, and why has
Two choices make the difference between a solution that works and one that almost works:
Map, not a plain object. Object keys are always strings, socache[1]andcache['1']are the same entry, and every object argument becomes'[object Object]'. AMapcompares keys by identity (SameValueZero), so1,'1'and each object get their own entry.cache.has(arg), notif (cache.get(arg)). A truthiness check treats a stored0,false,''orundefinedas a miss and callsfuncagain every time.
Complexity
O(1) on average per call on top of func itself. Memory grows by one entry for every distinct argument, and nothing is ever removed.
Follow-ups interviewers ask
- Several arguments: build a key from all of them, such as
JSON.stringify(args)for primitives, or a tree of nestedMaps (one level per argument) to keep identity semantics. - Custom key: accept a
resolver(...args)that returns the cache key, like Lodash'smemoize. - Memory leaks: a cache that never forgets can grow forever. Use a
WeakMapfor object arguments, or evict old entries with an LRU cache. - Async functions: cache the promise itself, so concurrent callers share one request, and remove it if it rejects.
Reference solution
/**
* @param {Function} func
* @returns {Function}
*/
export default function memoize(func) {
const cache = new Map()
return function memoized(arg) {
if (cache.has(arg)) return cache.get(arg)
const result = func(arg)
cache.set(arg, result)
return result
}
}export default function memoize<Arg, Result>(func: (arg: Arg) => Result): (arg: Arg) => Result {
const cache = new Map<Arg, Result>()
return function memoized(arg: Arg) {
if (cache.has(arg)) return cache.get(arg) as Result
const result = func(arg)
cache.set(arg, result)
return result
}
}