const factorial = function(n, acc = 1){
if (n < 2) {
return acc;
}
return factorial(n - 1, n * acc);
};
const factorial_normal = function(n){
if (n < 2) {
return 1;
}
return n * factorial_normal(n - 1)
};
console.log(factorial(8956)); // RangeError: Maximum call stack size exceeded
console.log(factorial_normal(8960)); // Infinity
It's just a simple factorial function with javascript. But I got a RangeError with the first function, which i do think it was a better solution cause i think it is faster and more stack-save. Is there something different in these two function that i've ever been known. Please help me, thanks.
Because Node.js doesn't support tail call optimization, both of these functions will throw the RangeError: Maximum call stack size exceeded error at some point. When this will happen depends on two quantities: the maximum allowed size of the stack and the size of each individual stack frame. By default, the size of the stack is set to some constant value, which you can get by running the following command:
node --v8-options | grep -e '--stack-size' -A 1
So, the only parameter left is the size of the stack frame. factorial stores two variables on the stack on each function call - acc and n. Whereas factorial_normal stores only one - n. It means that factorial will run out of stack space sooner than factorial_normal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With