function memoizeOnce(fn) {
let called = false, result
return (...args) => {
if (!called) { called = true; result = fn(...args) }
return result
}
}
const expensive = memoizeOnce(x => x * 1000)
expensive(7) // β 7000 (fn called)
expensive(99) // β 7000 (cached)Memoization via closures caches the first return value in a private variable, preventing redundant computation on subsequent calls.
Create a function that wraps another function and caches its result on first call. Subsequent calls return the cached result regardless of arguments.
Challenge: Create a memoizeOnce(fn) function that returns a wrapper. The first call to the wrapper executes fn with the given arguments and caches the result. All subsequent calls return the cached result without calling fn again.
Example:
let callCount = 0
const fn = (x) => { callCount++; return x * 2 }
const memoized = memoizeOnce(fn)
memoized(5) // calls fn, returns 10, callCount = 1
memoized(99) // returns cached 10, does NOT call fn