JS Built-ins
DesignPatternsintermediate

Decorator β€” Once

πŸ“– Usage Example
function once(fn) {
  let called = false, result;
  return function(...args) {
    if (!called) { called = true; result = fn.apply(this, args); }
    return result;
  };
}

The once decorator ensures a function executes only on the first call.

Decorator Pattern β€” Execute Once

A decorator can ensure a function only runs once, then returns the cached result.

Challenge: Implement an once(fn) decorator that wraps a function. The first call executes fn, but subsequent calls return the cached result without executing fn again.

Example:

let callCount = 0
const fn = (x) => { callCount++; return x * 2 }
const o = once(fn)
o(5) // calls fn, returns 10, callCount = 1
o(99) // returns cached 10, callCount still 1
πŸ’‘ Hints (4)
  • β€’ Use a flag to track if function was called
  • β€’ Store result in closure
  • β€’ Return cached result after first call
  • β€’ Do not call original function if already called