Antonio Ortiz - 10 months ago 29

Javascript Question

I am working through this coding challenge on Free Code Camp

`We'll pass you an array of two numbers.`

Return the sum of those two numbers and all numbers between them.

The lowest number will not always come first.

They suggest to use

`Math.max(), Math.min(), Array.reduce()`

`function sumAll(arr){`

var index0 = arr[0], index1 = arr[1], counter = 0, sum = 0, val;

if(index0 < index1){

counter += index0;

while(counter <= index1){

val = index0++;

sum += val;

counter++;

}

} else if(index0 > index1){

counter = 1;

counter += index0;

while(counter >= index1){

val = index1 + 1;

sum += val;

counter--;

}

}

return sum;

}

Basically this works save for when you try:

`sumAll([10, 5]) //I get 42, rather than 45`

So my two questions are the following:

Am I correct in the fact it's getting clunky?

And should I have used the aforementioned methods which were recommended?

I think I just got excited when stuff when I got things to work but now I feel I am going down a rabbit hole with another potential condition..

Thanks in advance!

Answer

You could use `min`

, `max`

and one `loop`

```
var sumAll = function(arr) {
var sum = 0,
min = Math.min.apply(null, arr),
max = Math.max.apply(null, arr);
for (var i = min; i <= max; i++) {
sum += i;
}
return sum;
}
console.log(sumAll([10, 5]))
```