FrontendPro

7Implement a once() function using closures

easyAbout 15 minutesCodingclosureshigher-order-functions

Problem

Implement once(fn). It returns a new function that calls fn the first time it is called and returns its result. Every later call returns that same first result without calling fn again.

const init = once(() => {
  console.log("initialising");
  return 42;
});
init(); // logs "initialising", returns 42
init(); // returns 42, logs nothing

Requirements

  • fn runs at most once, however many times the wrapper is called.
  • Forward the arguments and the this value of the first call.
  • Later calls return the first call's result.
  • Each call to once creates an independent wrapper.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

Declare called and result inside once. Every wrapper gets its own pair, and nothing outside can change them.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever