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
fnonly on the first call - Returns the result from the first invocation
- Returns the same result for all subsequent calls
- Preserves the
thiscontext and arguments
Example
Input
const init = once(() => {
console.log('initialized');
return 42;
});
init();
init();
init();
Output
initialized(Return value is always 42)
Expected Behavior
fnis executed only once- Subsequent calls do not re-execute
fn - First return value is reused
- Arguments and
thisare 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)