Run a Function Only Once
ClosuresHigher-Order Functions
Write once(fn), a wrapper that lets fn run a single time.
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
let runs = 0;
const connect = once((host) => {
runs += 1;
return 'connected to ' + host;
});
[connect('alpha'), connect('beta'), runs];Output
['connected to alpha', undefined, 1]Explanation
Only the first call reaches the original. The second returns undefined without running it, so runs stays at 1.
Constraints
- fn can take any number of arguments, and the first call passes them all through
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: Run a Function Only Once
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