Skip to content

Instantly share code, notes, and snippets.

@jtrein
Last active September 21, 2017 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtrein/16be11abb5766a76efe48fbd7f5079c7 to your computer and use it in GitHub Desktop.
Save jtrein/16be11abb5766a76efe48fbd7f5079c7 to your computer and use it in GitHub Desktop.
Sum of all numbers in range in JavaScript
const sumAll = (arr) => {
// get our largest and smallest int's
const max = Math.max.apply(null, arr);
const min = Math.min.apply(null, arr);
// how many slots are there to add?
const slots = (max - min) + 1;
// create sparse array with number of slots found
const sumArr = Array(slots);
// set an initial counter to fill the array with (increments inside `for` loop)
let counter = min - 1; // i.e. 22 to make incrementing easy inside the `for` loop
// fill sparse array
for (let i = 0; i < sumArr.length; i += 1) {
sumArr[i] = counter += 1;
}
// add the current number in the array to the previous result. We begin with 0.
const sumOfAll = sumArr.reduce((acc, next) => {
return acc + next;
}, 0);
return sumOfAll;
}
// example usage
sumAll([23, 46]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment