I have this code, which is counting array elements sum with recursion, but when the array is too big it throwing Maximum call stack size exceeded error.
var a = new Array(10 ** 7); a.fill(0); function sum(arr, i = 0) { if(i === arr.length) { return 0; } return arr[i] + sum(arr, i + 1); } sum(a); So I need to change it somehow to work normally for all cases and I thought I can make it work asynchronously with Promises, but it always returning Promise pending.
var a = new Array(10 ** 7); a.fill(0); var sum = (arr, i = 0) => new Promise((resolve) => { setTimeout(() => { if(i === arr.length) { return resolve(0); } return sum(arr, i + 1).then(el => el + arr[i]); }, 0); }); sum(a); How can I fix it?
Any help would be appreciated!
const sum = arr => arr.reduce((a, b) => a + b, 0)