Run a function only once
Some work must happen exactly once no matter how many components ask for it: booting an analytics SDK, requesting a permission, showing an onboarding modal. Sprinkling if (alreadyDone) flags around the codebase gets old fast, so you wrap the function instead.
Implement once(fn). It returns a new function that, on its first call, invokes fn with the same this and the same arguments it received, remembers the returned value, and returns it. Every later call returns that remembered value without invoking fn again — arguments passed to later calls are ignored. The cached value is returned even when it is falsy, such as 0 or null.
Arguments
fnFunction- The function to invoke exactly once.
Returns
Function — A wrapper that runs fn on its first call and returns the cached result forever after.
Examples
let calls = 0;
const init = once(() => { calls++; return "ready"; });
init(); // "ready", calls === 1
init(); // "ready", calls still 1
init(); // "ready", calls still 1The wrapped function fires exactly once no matter how many times you poke it.
const double = once((n) => n * 2);
double(5); // 10 — fn runs with 5
double(9); // 10 — later args are ignored, cached result winsWhat it has to do
- Invoke
fnon the first call only, however many times the wrapper is called. - Return the first call's return value from every subsequent call.
- Ignore the arguments given to calls after the first.
- Cache falsy return values such as
0just as reliably as truthy ones. - Preserve
thisso the wrapper works as an object method.
Notes
- Guard on a boolean flag, not on
result != null—0,null, andundefinedare all legitimate cached values. - Use
fn.apply(this, args)and a regular (non-arrow) wrapper so method-style calls keep their receiver.
Stuck? The javascript course covers everything this challenge needs.
- 1.invokes the wrapped function only once
- 2.ignores arguments from later calls
- 3.caches a falsy result
- 4.preserves this when used as a method
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.