Implement once(fn). It returns a new function, a wrapper, that calls fn at most one time.
- The first call runs
fnwith that call's arguments and returns its result. - Every later call returns the result of the first call without running
fnagain. Their arguments are ignored. fnruns with the samethisthe new function was called with.- The first result is reused even when it's
undefinedor another falsy value. A falsy value acts likefalsein anif, for example0,''orfalse. - Each call to
oncemakes a new, independent wrapper. Wrappers don't share state.
Input: const init = once(() => { console.log('setup'); return 42; });
init(); init();
Output: logs 'setup' once; both calls return 42
Input: const f = once((a, b) => a + b);
f(2, 3); f(10, 20);
Output: 5, then 5The second call's arguments are ignored.