Last active
September 21, 2017 07:12
-
-
Save jtrein/16be11abb5766a76efe48fbd7f5079c7 to your computer and use it in GitHub Desktop.
Sum of all numbers in range in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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