AniUI Academy

Run a function only once

easyFunctions & Closures+150 XPPractice

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 1

The 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 wins

What it has to do

  • Invoke fn on 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 0 just as reliably as truthy ones.
  • Preserve this so the wrapper works as an object method.

Notes

  • Guard on a boolean flag, not on result != null — 0, null, and undefined are all legitimate cached values.
  • Use fn.apply(this, args) and a regular (non-arrow) wrapper so method-style calls keep their receiver.
Asked atMicrosoftAtlassian

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.