sumAll([4,1]) should return 10 because sum of all the numbers between 1 and 4 (both inclusive) is 10.
tests:
- text: <code>sumAll([1, 4])</code> should return a number.
testString: assert(typeof sumAll([1, 4]) === 'number');
- text: <code>sumAll([1, 4])</code> should return 10.
testString: assert.deepEqual(sumAll([1, 4]), 10);
- text: <code>sumAll([4, 1])</code> should return 10.
testString: assert.deepEqual(sumAll([4, 1]), 10);
- text: <code>sumAll([5, 10])</code> should return 45.
testString: assert.deepEqual(sumAll([5, 10]), 45);
- text: <code>sumAll([10, 5])</code> should return 45.
testString: assert.deepEqual(sumAll([10, 5]), 45);
My Soln:
function sumAll(arr) {
let lowerBound;
let upperBound;
let sum=0;
if(arr[0]<arr[1]){
upperBound=arr[1];
lowerBound=arr[0];
} else{
upperBound=arr[0];
lowerBound=arr[1];
}
for(let i=lowerBound;i<=upperBound;i++){
sum+=i;
}
return sum;
}
sumAll([1, 4]);function sumAll(arr) {
let biggerNumber = Math.max(...arr);
let smallerNumber = Math.min(...arr)
let total = biggerNumber + smallerNumber
for (let i = smallerNumber + 1; i < biggerNumber; i++) {
total += i
}
return total
}Other possible solns:
return sum all numbers in a range - stackoverflow
Sum all numbers in a range - codereview.stackexchange
function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
return Array.apply(null, Array(max-min+1)) // get array of correct size
.map(function(_, b) { return b+min; }) // change it to have correct values
.reduce(function(a, b) { return a+b; }); // and sum it
}Here is a problem- What is Array.apply actually doing
See also Array() constructor