CodePark/ problems / once
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Closures and higher-order functions

once

easyabout 10 minutes in an interview

Implement once(fn). It returns a new function, a wrapper, that calls fn at most one time.

  • The first call runs fn with that call's arguments and returns its result.
  • Every later call returns the result of the first call without running fn again. Their arguments are ignored.
  • fn runs with the same this the new function was called with.
  • The first result is reused even when it's undefined or another falsy value. A falsy value acts like false in an if, for example 0, '' or false.
  • Each call to once makes 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.