JS Built-ins
Closuresadvanced

Closures β€” Memoize single value

πŸ“– Usage Example
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.

Cache Function Result

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
πŸ’‘ Hints (3)
  • β€’ Use a flag to track if the function has been called
  • β€’ Store the result in a closure variable
  • β€’ Always return the cached result after first call