Skip to content
Exercise · Closures and this · lesson 9 of 11

Exercise: call once

Write a function function once(fn) that returns a new function. On its first call, the new function calls fn with all of its arguments and returns its result. Later calls do not call fn and return the result of the first call.

  • const f = once((x) => x * 2), then f(5) → 10
  • the next call f(7) → 10
  • once((a, b) => a + b)(2, 3) → 5

Constraints: there are zero to three arguments; the result of the first call is returned even when it is 0; every function created by a separate call of once has its own first call.

Do not add extra imports unless the task says so explicitly.

once.js — javascript
javascript · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way