Simple solution for Sum All Numbers in a Range challenge

Simple solution for Sum All Numbers in a Range challenge
0

#1

Here’s my solution for this challenge:


function sumAll(arr) {
    
var myArray = arr;

 maxValue = Math.max.apply(null, myArray);

 minValue = Math.min.apply(null, myArray);

 var newArray = Array();

newArray.push(minValue, maxValue);

var ourTotal = 0;

for (var i = minValue; i <= maxValue; i++){
    
    ourTotal += newArray[0]++;
    
}  
    
    return ourTotal;
}

sumAll([1, 4]);



#2

I refactored your solution and put some comments about the changes I made:

function sumAll(arr) {
    
 // var myArray = arr;  // this line not needed

 maxValue = Math.max.apply(null, arr); // use the original array (arr)

 minValue = Math.min.apply(null, arr);  // use the original array (arr)

 // var newArray = Array(); // this line not needed

 // newArray.push(minValue, maxValue); // this line not needed

 var ourTotal = 0;

 for (var i = minValue; i <= maxValue; i++){
    
    ourTotal += i;  // changed newArray[0] to i
    
}  
    
    return ourTotal;
}

sumAll([1, 4]);

#3

Hi. thanks, forgot to clean up the code before i pasted it here.


#4

This is how I do it.

function sumOf(min, max) {
    return (max-min+1) * (min+max) / 2;
}

function sumAll(arr) {
    return sumOf(Math.min.apply(null,arr), Math.max.apply(null,arr));
}