AniUI Academy
easy+150 XPPractice

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.

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.

Your workspace

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.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.