Marciano Marciano - 2 months ago 8
Javascript Question

Javascript : The sum of its range

I'm currently following the exercises from Eloquent Javascript and got a little stuck at one exercise. Let me explain it with code:

var _numberArray = [];

function range(start, end, step)
{
console.log(_numberArray);


if (!step)
{
step = 1;
}

if (step < 0)
{
for(var i = start; i >= end; i -= step)
{
_numberArray.push(i);
console.log(_numberArray);


}
}
else
{

for(var i = start; i <= end; i += step)
{
_numberArray.push(i);
console.log(_numberArray);
}
}


return _numberArray;
}


function sum(array)
{
var total = 0;
for (var i = 0; i < array.length; i++)
{

total += array[i];

}
return total;

}

console.log(sum(range(42,14,-2)));


So I created the range function where I check if the step argument has been set. If not, set the default step variable to 1. If step is smaller than 0, be sure to loop where as long as the first argument is bigger the second, and decrement the value with the step amount given. This is the same for incrementing.

However, this code causes to crash only when I use negative values. So when I do "sum(range(22,6,-2));" the code crashes. The other way round "sum(range(6,22,2));" it does work. Also when I replace:

for(var i = start; i >= end; i -= step)
{
_numberArray.push(i);
console.log(_numberArray);


}


For:

for(var i = start; i >= end; i--)
{
_numberArray.push(i);
console.log(_numberArray);


}


It does work again! Can someone help me out and give me some understanding why it crashed and why the last method does work?

Thanks.

Answer

Since the step value is negative, and you're iterating downwards, you need to add it, not subtract it:

for(var i = start; i >= end; i += step) 

Subtracting a -2 is the same as adding 2, so you're going 42, 44, 46, ... And that value is always more than "end" (14), hence the infinite loop.