Skip to content

Instantly share code, notes, and snippets.

@sionleroux
Last active January 31, 2016 21:37
Show Gist options
  • Save sionleroux/03fe6fc0acb0f16431a6 to your computer and use it in GitHub Desktop.
Save sionleroux/03fe6fc0acb0f16431a6 to your computer and use it in GitHub Desktop.
Functional solution to Free Code Camp's "Sum All Numbers in a Range" challenge
function sumAll(x) {
return Array.from(
{length: Math.max(...x) - Math.min(...x) + 1},
(v,k) => k + Math.min(...x)
).reduce((s, c) => s + c)
}
@sionleroux
Copy link
Author

  1. function header expected by Free Code Camp's tests, x is an array
  2. create a new array to hold our range (docs), note: we return the final summed result
  3. elements will be (max - min + 1), the +1 is needed to include the upper value, e.g. 5..10 = (10 - 5 + 1) = (5 + 1) = 6

  4. lambda populates array with incrementing values starting from min (the array keys k already increment)
  5. reduce array by summing current number c into sum s
  6. Note: min() and max() expect several numbers as arguments, not a single array, ...x is how we spread x into arguments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment