#Closures#Higher-Order Functions

Allow One Function Call

A once wrapper: the first call runs, every call after it does nothing.

By Pratik RaiEasy

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

Input:

JSfile.javascript
1const add = once((a, b) => a + b); 2add(1, 2); // 3 3add(3, 4);

Output:

undefined

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.

Goal: Run the original exactly once, whatever the caller does afterwards.

Source

Frequently asked questions

What does a once wrapper do?
It lets a function run exactly one time. The first call goes through and returns its result; every later call is ignored.
Why set the flag before calling the original?
So a first call that throws still counts as the call. Setting it afterwards leaves the wrapper armed, and the next call runs the failing function again.
Should later calls return the cached result?
That is a design choice worth stating. This version returns `undefined`, while Lodash's `once` caches and returns the first result forever. Interviewers ask which you implemented to see whether you noticed there was a decision.
What is this useful for?
One-time initialisation, an event handler that must not double-submit a form, or a cleanup that would throw if it ran twice. It is a closure question dressed up as a utility.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Memoize

Cache a function by its arguments so the same call never computes twice.

JavaScript · ES6Pratik Rai ·

JavaScript

Function Composition

Fold an array of functions into one, applied right to left.

JavaScript · ES6Pratik Rai ·

JavaScript

JS Output Challenges

Test your JavaScript skills by predicting console output for tricky code snippets. Covers hoisting, closures, this binding, async operations, and event loop quiz questions.

JavaScript · ES6Pratik Rai ·