once
EasyP2Coding
Implement once(fn), which returns a wrapper around fn that lets it run only the first time.
- The first call runs
fnwith the wrapper's arguments andthis, and returns its result. - Every later call ignores its arguments, does not run
fnand returns the same result as the first call. - The result is remembered even if it is
undefinedor 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.