Question:
I have an issue here, I’m trying to create a function that sums up all integers from a deeply nested array, but it’s failing an unit test, which means something is not right. Here is my function:c
is called, your call stack will contain all the memory for variables used in c
. When c
calls b
, all the memory for variables used in b
are added to the stack. When b
calls a
all the memory for variables used in a
are added to the stack. When a
finishes executing (so when you get to ‘some code’), variables related to a
are deallocated and removed from the stack.The problem you have here is that every time your function recursively calls itself, more memory is being allocated onto the stack. to stop this kind of code using up all the system memory, the runtime limits how big the stack can get – which is why you are hitting this error.
To pass this test, you need a solution which doesn’t call itself every time it hits an array within an array. Here’s my solution, effectively using an array as a buffer; each time I hit a nested array I add it to the buffer. Once I finish processing the outer array, I then check if there is any arrays left in the buffer.
export const arraySum = (arr) => {
let sum = 0;
const buffer = [arr];
while (buffer.length > 0) {
const next = buffer.shift();
for (let i = 0; i < next.length; i++) {
if (typeof next[i] === "number") sum = sum + next[i];
else if (Array.isArray(next[i])) buffer.push(next[i]);
}
}
return sum;
};
[/code]
If you have better answer, please add a comment about this, thank you!