Allow One Function Call
ClosuresHigher-Order Functions
Write once(fn) returning a function that calls fn at most once.
The first call passes its arguments through and returns the result. Every later call returns undefined and does not invoke fn again.
Examples
Example 1
Input
const add = once((a, b) => a + b);
add(1, 2); // 3
add(3, 4);Output
undefinedExplanation
The second call is ignored entirely.
Constraints
- 0 <= args.length <= 100
Notes
- Note that later calls return `undefined` rather than the cached first result — Lodash’s `once` caches, and interviewers ask which you built.
Hints
Editorial: Allow One Function Call
One flag in a closure
once is a two-line function that is really a closure question. The state has to live outside the returned function so it survives between calls.
Approach
Flip the flag before invoking, so a throwing first call still counts as the call.
Implementation
function once(fn) { let called = false; return function (...args) { if (called) return undefined; called = true; return fn.apply(this, args); }; }
Worth knowing
Later calls return undefined rather than the cached first result. That is a deliberate difference from Lodash's once, which caches and returns the same value forever — interviewers ask which one you built and why.
Each wrapper gets its own flag, so wrapping the same function twice gives two independent one-shot functions.
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it