[Javascript] Proper Tail Calls

Zhentiw發表於2024-08-07

Docs: https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit/

/*
This is a recursive function without PTC
*/
function fatorial(n) {
    if (n === 0) {
        return 1
    } else {
        return n * fatorial(n-1)
    }
}

console.log(fatorial(5)); // 120

/*
This is recursive function with PTC
*/
function fatorialPTC(n, acc = 1) {
    if (n === 0) {
        return acc
    } else {
        return fatorialPTC(n-1, n * acc)
    }
}
console.log(fatorialPTC(5)); // 120

The function with PTC will run much faster than without PTC.

PTC is defined as:

  • 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.

相關文章