// recursion
// iterative way
const sumBelow = number => {
let result = 0;
for(let i = 0; i <= number; i++) {
result += i;
}
return result;
}
// the recursive way
const sumBelow = (number, sum = 0) => (
number === 0
? sum
: sumBelow(number - 1, sum + number)
)
// possible Problem with recursion above:
sumBelow(100000); // => Uncaught RangeError: Maximum call stack size exceeded
// Large recursive loops with trampolines
const trampoline = fn => (...args) => { // takes a function (fn) as argument (this is the
let result = fn(...args); // recursive function it is going to wrap) and
// returns a new function. Within this new function,
while (typeof result === 'function') {// the recursive function is called. The loop runs as
result = result(); // fn returns another function. Once fn resolves into
} // a value, we stop running the loop and return the value.
return result;
}
// The recursive function as to be slightly modified in order to be used by the
// trampoline function:
const sumBelowRec = (number, sum = 0) => (
number === 0
? sum
: () => sumBelowRec(number - 1, sum + number) // The recursive portion now returs an anonymus
); // function and can be managed by the while-loop
// of the trampoline function
// Last step: wrapping sumBelowRec in the original function
const sumBelow = trampoline(sumBelowRec);
sumBelow(100000); // => 5000050000