Not the most complicated algorithm but another one to add to the collection

Tim Parsons
Sep 2, 2018 · 2 min read

Day 13/100 of #100daysofcode

Quiet day yesterday, didn’t get to to work on anything which was nice to take a break for a bit and spend time with the family.

Got back to it today and used one of my favorite resources, the newly updated FreeCodeCamp. Since they updated, it’s so much better and especially the algorithms. Today I worked on the Intermediate ones and started with Sum All Numbers in a Range. Not too bad.

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.

In my mind, my first thought was to use the .sort() method to arrange them in ascending order, then loop through the array adding each number to a variable of result. This is usually where I start to question myself and think I’m doing it the wrong way. Well, I don’t know if I was but I decided to do it another way.

Instead, I created a variable max with the highest number in the array and a variable min with the lowest number in the array. From there I would loop through the array using those variables, adding the index to the result variable and returning it at the end.

function sumAll(arr) {
const max = Math.max(...arr);
const min = Math.min(...arr);
let result = 0;
for(let i = min; i <= max; i++) {
result += i;
}
return result;
}
sumAll([1, 4]);
woot woot!

Not the most complicated algorithm, but another one that helps me become the best software engineer I can be.

If you have any other thoughts/suggestions on a better answer, leave and an answer in the comments below.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade