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

Exercise: apply n times

Write a function function applyTimes(fn, n) that returns a new function of one argument x. The new function applies fn to x n times in a row, each time to the result of the previous application, and returns the last result.

  • applyTimes((x) => x + 1, 3)(0) → 3
  • applyTimes((x) => x * 2, 3)(1) → 8
  • applyTimes((x) => x * 2, 0)(7) → 7

Constraints: n is an integer from 0 to 20, and when n is 0 the new function returns x unchanged; fn takes one argument; the new function can be called many times, and each call starts over from its own x.

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

apply-n-times.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