yup, that works quite well. Now, a suggestion – the ES6 way of thinking is less about the “how” of things, and more about the “what”. The for
loop works, and works quite well, but you’re having to tell javascript explicitly how it is to iterate over the array, as well as telling it what you want done to each member.
But, with ES6, that changes. We no longer have to write the mechanisms to iterate over arrays, for example. We have higher-order functions like .map()
, .filter()
and .reduce()
. These will iterate over an array, without us having to specify the means that javascript will use to do so.
In the version of this I had written, I used three Array methods (in addition to the .sort()
, which I defined exactly as you did). I wanted to return an array, fill()
ed with empty members, which I then map()
ped to the range of values, and then reduce()
d to a single, sum, value.
Not saying AT ALL that your solution is wrong. It truly isn’t. But as you move on in your coding journey, you’ll find that there is always a different way to solve a problem.
What is meant by the best way, though? Is it the most elegant? The most time-efficient? It really depends on the needs. Here’s what I did:
- I wrote the same functionality as two functions,
sumAll()
and sumAll2()
. The first is using map/reduce, and the second is the straightforward for
loop.
- I wrapped the call to each one in a handy timing gadget,
console.time()
and console.timeEnd()
– not 100% perfect as a benchmark, but great for comparing.
function sumAll(arr) {
// First, order them least to greatest.
arr.sort((x, y) => {
return x - y;
});
/***
* The following chained series of functions does quite a lot:
* - create an empty Array of the length of our range,
* - fill() the array with undefined for each member,
* - map() the values from start to finish into each member,
* - reduce() the array to the single, sum, value.
***/
return Array(arr[1] - arr[0] + 1)
.fill()
.map((item, index) => arr[0] + index)
.reduce((sum, current)=>sum+current, 0);
}
function sumAll2(arr){
let sum = 0;
arr.sort((x, y) => {
return x - y;
});
for (let index = arr[1]; index >= arr[0]; index--) {
sum += index;
};
return sum;
}
// Wrapping the function call in time() and timeEnd() displays the
// elapsed time our function took.
console.time("sumAll");
console.info("Using map() and reduce: "+sumAll([20000, 1]) );
console.timeEnd("sumAll");
console.time("sumAll2");
console.info("Using a for loop: "+sumAll2([20000, 1]) );
console.timeEnd("sumAll2");
Interestingly, in this case, your way is MUCH faster. I used a pretty high number for our range, simply to drive home the difference, but it scales in both cases – yours is about seven times faster, every time.
Using map() and reduce: 200010000
sumAll: 7.228ms
Using a for loop: 200010000
sumAll2: 1.066ms
You can test this out with different values for sumAll() and sumAll2() on my repl.