Allow One Function Call
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
const add = once((a, b) => a + b);
add(1, 2); // 3
add(3, 4);undefinedConstraints
- 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
Allow One Function Call (reference solution)
One way to do it. The Editorial tab walks through why it is written this way.
Solution
1function once(fn) {
2 let called = false;
3 return function (...args) {
4 if (called) return undefined;
5 called = true;
6 return fn.apply(this, args);
7 };
8}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.