I have implemented the "Sum All Numbers in a Range" challenge from Free Code Camp quoted below.
The code works like a charm, but I don't think it's idiomatic. The challenge hints imply I should be using Math.max()
, Math.min()
and Array.reduce()
. In addition I used the spread operator from ES6 to simplify both Math
calls.
I'm looking for a more idiomatic way to solve this. I think it can be done in a one-liner, something like:
return arr.sort((function(a, b) { return a - b; })).reduce(function(a, b) { /* */ });
But I'm pretty sure I'm heading the wrong way with the above.
The challenge:
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.
The code:
function sumAll(arr) {
var out = 0;
for (var i = Math.min(...arr); i <= Math.max(...arr); i++) {
out += i;
}
return out;
}
Test cases:
sumAll([1, 4])
sumAll([4, 1])
sumAll([5, 10])
sumAll([10, 5])
Expected output:
10
10
45
45
return (a+b)*(b-a+1)/2;
\$\endgroup\$ – njzk2 Jan 18 '16 at 21:58