Sum Numbers in a range

Sum Numbers in a range
0

#1

Hello, I just solved the sum all numbers in a range challenge but I got a strange behavior in the process

I first did this…

var total = 0;
function sumAll(arr) {
  var min = Math.min.apply(null, arr);
  var max = Math.max.apply(null, arr);

  for(var i = min; i <= max; i++){
    total += i;
  }

  return total;
}
sumAll([5, 10]);

only the first test that checks if the output is a number passed, though the outputs were correct. However, when I did the following, which is basically changing the scope of the total variable, it was accepted

function sumAll(arr) {
  var min = Math.min.apply(null, arr);
  var max = Math.max.apply(null, arr);
  var total = 0;

  for(var i = min; i <= max; i++){
    total += i;
  }

  return total;
}
sumAll([5, 10]);

WHY???


#2

The reason the first one fails on the other tests is because the total variable is declared globally so it each time the function is called, it is not reset to 0 (like the 2nd version does).

See what happens in the following link:


#3

This is what I did. It works.

function sumAll(arr) {
  var sum = 0;
  if(arr[1]>arr[0]){
  for(var i = arr[0]; i <= arr[1]; i++){
    sum = sum + i;
    }
  }
  else{
    for(var j = arr[0]; j >= arr[1]; j--){
    sum = sum + j;
    }
  }
  return sum;
}

sumAll([4, 1]);

#4

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard.


#5

congrats.I will try with this later.


#6

I am wandering if there is a way to create the numbers without using for.....

I mean for example using map. Because as I understood map method return an array with the same input length.....

function sumAll(arr) {
let data = ([].concat(arr)).sort((a,b)=>a-b);
let newData = []

for (let i = data[0];i<=data[1];i++){
 newData.push(i)
}
return(newData.reduce((a,b)=>a +b));

}

sumAll([1, 4]);

#7

There is also a mathematical formula for adding all numbers from X to Y, which is very useful here, and lets you avoid a for loop completely.

(highestNumber - lowestNumber + 1) * (highestNumber + lowestNumber) / 2