[Javascript] Trampolines & Tail call
Blog: https://www.geeksforgeeks.org/es6-trampoline-function/
Stackoverflow problem for recursion:
const sumBelow = (number, sum = 0) => (
number === 0
? sum
: sumBelow(number - 1, sum + number)
)
sumBelow(100000);
// Uncaught RangeError: Maximum call stack size exceeded
The recursive function keeps adding entries to the JavaScript engines call stack until there’s no more room, and then we get an error (if you want to read a bit more about how the call stack works, feel free to check out this article).
Tail calls
One way to avoid blowing up the call stack is to use proper tail calls — these were added in the ES2015 spec. In order to use proper tail calls (PTC), a function satisfy the following conditions:
- You must be in
use strict
mode. - The recursive function call must be in tail position — that is, it is the very last thing to be evaluated before the
return
statement. For a detailed overview of what constitutes tail position, there’s a really nice dive into that in in this post.
Trampolines
Idea of Trampolines is that: inside a function, call another function which returns your a function. We have a while loop to keep calling the return function until it is no longer a function type. This helps to reduce our callstack.
const trampoline = fn => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
Usage:
const sumBelowRec = (number, sum = 0) => (
number === 0
? sum
: () => sumBelowRec(number - 1, sum + number) // return a function
)
const sumBelow = trampoline(sumBelowRec)
sumBelow(100000)
// returns 5000050000 🎉🎉🎉