Search code examples
javascriptrecursionfunctional-programmingsafaritail-recursion

Tail call optimization (TCO) not working in Safari


According to ES6 compatibility table, Safari has tail call optimization feature. Tried it and it fails just like any other browser 😭. Am I missing something?

function factorial(n, r = 1n) {
  return (n <= 1) ? r : factorial(n - 1n, n * r)
}

console.log(factorial(36000n))

Safari output:

RangeError: Maximum call stack size exceeded.


Solution

  • You need to run your program in strict mode.

    "use strict";
    
    function factorial(n, r = 1n) {
        return n <= 1n ? r : factorial(n - 1n, n * r);
    }
    
    console.log(factorial(36000n).toString());

    There are four conditions that need to be met in order for a function call to be considered a proper tail call.

    • The calling function is in strict mode.
    • The calling function is either a normal function or an arrow function.
    • The calling function is not a generator function.
    • The return value of the called function is returned by the calling function.

    Source: ECMAScript 6 Proper Tail Calls in WebKit by Michael Saboff