Okato
Okato

Reputation: 35

javascript Factorial function got RangeError

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.

Upvotes: 3

Views: 354

Answers (1)

danroshko
danroshko

Reputation: 466

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.

Upvotes: 3

Related Questions