Function Once

Implement once(fn) — a higher-order function that ensures fn is called at most once, no matter how many times the returned wrapper is invoked.

  • First call: Executes fn with the given arguments, caches and returns the result.
  • All subsequent calls: Ignores arguments and returns the cached result from the first call.
let callCount = 0;
const initialize = once(() => {
  callCount++;
  return 'initialized';
});

initialize(); // 'initialized'  (fn called)
initialize(); // 'initialized'  (fn NOT called — cached)
initialize(); // 'initialized'
callCount;    // 1

Real-World Uses

  • Lazy initialization — compute an expensive value only once
  • One-time event registration — prevent duplicate listeners
  • API calls on mount — avoid duplicate network requests
Examples
Input: [null,1,42]
Output: 42
Hints

Function Once

Implement once(fn) — a higher-order function that wraps fn so it executes at most once, returning the cached result on every subsequent call.