Description

Sometimes you want a function to execute only once, even if it is called multiple times.
This pattern is commonly used for initialization logic, event handlers, or setup code.

In this challenge, you’ll implement a once function that ensures a given function runs only on its first invocation.


Your Task

Implement a function once(fn) that:

  • Accepts a function fn
  • Returns a new function
  • Executes fn only on the first call
  • Returns the result from the first invocation
  • Returns the same result for all subsequent calls
  • Preserves the this context and arguments

Example

Input

const init = once(() => {
console.log('initialized');
return 42;
});

init();
init();
init();

Output

initialized

(Return value is always 42)


Expected Behavior

  • fn is executed only once
  • Subsequent calls do not re-execute fn
  • First return value is reused
  • Arguments and this are preserved
  • Original function is not modified

Constraints

  • Do not use global variables
  • Time complexity should be O(1) per call
  • Space complexity should be O(1)