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:
export const arraySum = (arr) => {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number") sum = sum + arr[i];
else if (Array.isArray(arr[i])) sum = sum + arraySum(arr[i]);
}
return sum;
};
And here is my unit test which is failing:
test("it should sum up from deeply nested arrays", () => {
type ValueOrArray = number | Array<ValueOrArray>;
const createDeeplyNestedArray = (depth: number): ValueOrArray => {
let retval: ValueOrArray = [1];
for (let i = 0; i < depth - 1; i++) {
retval = [1, retval];
}
return retval;
};
const NUMBER_OF_ELEMENTS = 100000;
const arr = createDeeplyNestedArray(NUMBER_OF_ELEMENTS);
expect(arraySum(arr)).toEqual(NUMBER_OF_ELEMENTS);
});