let sum = 0;
var runningSum = function (nums2) {
let result = []
while (result.length > 0) {
result.pop();
}
for (let i = 0; i < nums2.length; i++) {
sum += nums2[i];
result.push(sum)
}
return result
};
I get the following output:
runningSum([1,1,1]) //=> [1, 2, 3]
runningSum([1,1,1]) //=> [4, 5, 6]
I’m expecting the following output:
runningSum([1,1,1]) //=> [1, 2, 3]
runningSum([1,1,1]) //=> [1, 2, 3]
What am I doing wrong?
7
Answers
The problem is that each time runningSum is called, the variable sum is not reset to zero because it is defined outside of the runningSum function. This indicates that sum keeps the value from the prior call and keeps adding to the ongoing sum.
As the comment point out, you need to define the variable
sum
locally in your function and you can get rid of the while.By defining
sum
within your function, then it will be created new every time the function is called.If you happen to need a variable named
sum
outside the function, you can still do so. Despite having the same name, they are completely different variable that do not affect one another:You can simplify your code as it:
It’s great that others are simplifying your code (which should be done eventually), but this answer will show you why sum is not reset upon each call to the function. Since sum is set outside the function, the value is not reset. I moved it inside the function.
The problem is, you are declaring your
sum
outside of your function and never resetting it. So in your second call ofrunningSum
you are already starting with asum = 3
instead ofsum = 0
But actually, you don’t need that variable at all. For the value of
result[i]
just add the previous element in the result array and the current element in the input array.result[i] = result[i-1] + arr[i]
. For indexi = 0
you have to take precautions and add a fallback to0
, becauseresult[-1]
will giveundefined
just write something like that (let sum=0 goes inside function)
The
sum
variable should not exist globally (but within the function), otherwise it will never be reset to 0.Maybe you can simplify your function using a
reducer
, something like: