A friend of mine hosts meetups for the Free Code Camp, which describes itself as:
We’re an open source community of people who learn to code and help nonprofits.
He organises casual meetings in coffee shops to allow participants to work on their assignments in a nice environment and help each other. If you’re looking to learn programming I recommend finding a Free Code Camp group in your area.
[3, 1] should result in
1 + 2 + 3 = 6. As a hint, it’s recommended you read the documentation for
His solution worked, it was clearly written and well structured. It involved defining two variables for the smaller and bigger number, for example by
var smaller = Math.min(arguments, arguments), then using those values in a “
for loop” which pushed an element into an array, where the value would come from the index of the current iteration in the loop. Finally he would sum this array using a callback using a simple callback that adds up the values. This uses all of the functions mentioned in the hints.
For reference here is a similar solution by someone else, sorting the input instead of using
The main place I saw for improvement was the
for loop. If we could avoid it, we could elegantly chain all our logical steps into a single statement, clearly describing our function. Using some nice syntactic sugar from ES6, I was able to distil the algorithm to the following:
- function header expected by Free Code Camp’s tests,
xis an array
- create a new array to hold our range (docs), note: we return the final summed result
- # elements will be
(max - min + 1), the
+1is needed to include the upper value, e.g.
5..10 = (10 - 5 + 1) = (5 + 1) = 6
- lambda populates array with incrementing values starting from min (the array keys
- reduce array by summing current number
max()expect several numbers as arguments, not a single array,
...xis how we spread
P.S. here’s an even shorter solution!