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.

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.

Where it's been asked

  • Microsoft
  • Atlassian

From public interview reports — a problem very like this one has shown up in a round at these companies. Not an exhaustive list.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...

Ready to check it?

4 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

Need a nudge?

Reveal a conceptual hint or the reference solution. Both were written and reviewed with the problem — no runtime magic.

Discussion

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

No comments yet. Be the first to say something.