1

Here is a repeat function that recursively calls itself

  const repeat = x => f => {
    if (x > 0) {
      f()
      return repeat (x - 1) (f)
    }
  }
  

The problem with it is it can cause stack overflow. I was wondering if I can rewrite it using tail call recursion so it can be stack-safe.

Joji
  • 4,703
  • 7
  • 41
  • 86
  • JavaScript doesn’t have proper tail calls in its spec yet and the only major engine that does tail call elimination is Safari’s (IIRC), so no, you can’t. Have to use a loop. – Ry- Oct 08 '21 at 19:58
  • 2
    To elaborate this a bit, iirc, tail calls are [in the spec since ES6](https://tc39.es/ecma262/#sec-tail-position-calls), but there are [issues](https://stackoverflow.com/questions/42788139/es6-tail-recursion-optimisation-stack-overflow), which led to [barely any major browser implementing them](https://kangax.github.io/compat-table/es6/). – ASDFGerte Oct 08 '21 at 20:20
  • Your function already does use tail recursion. – Bergi Oct 08 '21 at 23:40

0 Answers0