Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
Once
easy10 min
Wrap a callback so it runs at most once, preserving the first invocation and reusing its result on later calls.
Requirements
Implement once(callback), returning a normal function wrapper. Creating the wrapper must not invoke callback.
On the first call, forward all arguments and the wrapper receiver (this), invoke callback exactly once, and return its result. Later calls reuse that exact result, ignoring new arguments and receivers.
Cache any result, including undefined, false, 0, objects, and promises. Do not await or clone results. Each wrapper has independent state.
If the first invocation synchronously throws, cache the original thrown value and rethrow it on later calls without retrying callback.
Mark the invocation as started before calling callback. A recursive call to the same wrapper while its first callback is running returns undefined and must not invoke callback again. Assume a valid callable callback.
Examples
Example 1
Input: const run = once((a, b) => a + b);
run(2, 3);
run(10, 20);
Output: 5
5
Example 2
Input: let calls = 0;
const run = once(() => ++calls);
run(); run(); run();
calls;
Output: 1
Allow at most one callback invocation per wrapper.
What the tests check
Is lazy and invokes the callback only once
Uses only the first arguments
Forwards the first receiver
Caches falsy and undefined results
Preserves returned object identity
Keeps different wrappers independent
Caches and rethrows the original error without retrying
Preserves falsy thrown values
Prevents recursive callback execution
Reuses a promise without awaiting or recreating it