Q25: Implement a once() utility that allows a function to execute only once.

Difficulty:BeginnerTopic:Closures

Answer

A once() utility wraps a function so that its implementation executes at most one time. Subsequent calls return the result from the first execution.

function once(fn) {
  let called = false;
  let result;

  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }

    return result;
  };
}

let count = 0;

const initialize = once(() => {
  count++;
  return "initialized";
});

console.log(initialize()); // initialized
console.log(initialize()); // initialized
console.log(count); // 1

Explanation

A closure stores the called flag and the first result. Once the function has run, subsequent calls skip execution.

The flag is set before calling fn, which prevents reentrant calls from executing it again. In this implementation, if fn throws, later calls will not retry it. That behavior is a deliberate design choice and can be changed if retries are required.

Key Takeaways
  • Once uses a closure to remember whether the wrapped function has executed.
  • The wrapper can preserve the first result and the calling receiver.