Skip to content
Onsite

once

EasyP2Coding

Implement once(fn), which returns a wrapper around fn that lets it run only the first time.

  • The first call runs fn with the wrapper's arguments and this, and returns its result.
  • Every later call ignores its arguments, does not run fn and returns the same result as the first call.
  • The result is remembered even if it is undefined or another falsy value.

Example 1

Input
const init = once(() => { log('setup'); return 42; }); init(); init();
Output
'setup' is logged once; both calls return 42

Constraints

  • fn is a function.
  • Calls are synchronous.

Hints

Run checks the 3 visible tests, Submit all 8.