Sum All Numbers in a Range
Mohammed Awad
Posted on May 10, 2023
DESCRIPTION:
We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.
Examples
sumAll([1, 4]) `should return 10`.
sumAll([10, 5]) `should return 45`.
My approach for solving this problem:
- find the min and max value in the array.
- fill the array with range from min to max.
- if not return sliced str with num length.
- get the summation of the array with reduce().
My solution:
function sumAll(arr) {
const minNumber = Math.min(...arr);
const maxNumber = Math.max(...arr);
return new Array(maxNumber - minNumber + 1)
.fill()
.map((num,index)=> minNumber+index)
.reduce((perv,num) => perv + num)
}
sumAll([1, 4]);
Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!
Follow Muhmmad Awd on
If you have any questions or feedback, please feel free to contact me at
💖 💪 🙅 🚩
Mohammed Awad
Posted on May 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.