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
fnwith 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
Input: [null,3,10]
Output: 10
Hints
Declare `let called = false` and `let result` in once's scope.
The returned wrapper checks `called` before invoking fn.
On first call, set `called = true`, call fn, store the result, return it.
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.