Recursive Function - RangeError: Maximum call stack size exceeded - JavaScript

112 Views Asked by At

I'm trying to make a set of functions that add the digits of a number. But with giant numbers, the maximum amount of calls is exceeded. I would like to resolve this issue.

My code - (Example of error in calling the function at the end.):

const recursiveSum = (arr, iter) => {
  let strNums = arr.reduce((acc, curr) => acc + curr, 0);
  let arrNums = strNums.toString().split('').map(Number);
  let res = arrNums.reduce((acc, curr) => acc + curr, 0);
  let newArr = res.toString().split('');

  const resLength = res.toString().split('').length;

  if (iter === 0 || resLength === 1) {
    return res;
  } else {
    return recursiveSum(newArr, iter - 1);
  }
}

function getTheP(arr, k, p) {
  console.log(k);
  arr.map(num => {
    p.push(num);
  });

  if (k === 0) {
    return p;
  } else {
    getTheP(arr, --k, p);
  }
}

function superDigit(n, k) {
  let p;
  const splitArr = n.toString().split('');

  p = getTheP(splitArr, k, []);

  const response = recursiveSum(p, k);

  return console.log(response);
}

superDigit('4757362', 10000);

0

There are 0 best solutions below