## DEV Community is a community of 797,169 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Solving "Sum All Numbers in a Range" / freeCodeCamp Algorithm Challenges

On your solution, you may change the original array destructively.

const arr = [5, 0]
sumAll(arr)  // 15
arr // [ 0, 5 ]

To avoid this, you can use [...arr] or concat() method.

function sumAll(arr) {
arr = [...arr]
let fullArr = [];
arr.sort((a,b) => a - b);
for (let i = arr[0]; i <= arr[1]; i++) {
fullArr.push(i);
}
let sum = fullArr.reduce((acc, currVal) => {return acc + currVal}, 0);
return sum;
}

const arr = [5, 0]
sumAll(arr)  // 15
arr // [ 5, 0 ]

And, my trials here:

const sumAll = ([a, b]) =>
closedRange(a, b)
.reduce(
(acc, e) => acc + e
, 0
)

const closedRange = (a, b) =>
a > b ? [...Array(a - b + 1).keys()]
.map(e => a - e )
: [...Array(b - a + 1).keys()]
.map( e => a + e )

Or, more simply:

const sumAll = ([a, b]) =>
(a + b) * (Math.abs(a - b) + 1) / 2