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
undefined
Explanation
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

Read the full write-up for Allow One Function Call
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it