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

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