Trying to correct Sum All Numbers in a Range solutions

Hey guys, I noticed that none of the solutions for this challenge take the actual conditions into account.
They ignore the fact that the array has only 2 items and they don’t return a sum of num1 and num2 when they are equal.
I.e. [4, 4] returns 4 instead of 8 for all of the solutions.

I tried to correct the recursive one just to practice, but it’s returning 14 instead of 10 for some reason.

edit: chatgpt suggests using num1 + 1 !== num2 for the base case and this works, but I still can’t comprehend the logic behind that.

Your code so far

function sumAll(arr) {

  const [num1, num2] = arr.sort((a, b) => a - b);

  return num1 !== num2
  ? num1 + sumAll([num1 + 1, num2])
  : num1 + num2;

}

console.log(sumAll([1, 4]));
sumAll([1, 4]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42

Challenge: Intermediate Algorithm Scripting - Sum All Numbers in a Range

Link to the challenge:

Notice that in the recursive calls, the last one for the [1, 4] case will be sumAll([4, 4]), which with the changes results in 8.

Yes, you’re right. The last one (or the first one) should be 3 + 4.
Somehow it was easier for me when I rewrote it as num1 != (num2 - 1):

function sumAll(num1,  num2) {
  return (num1 != (num2 - 1))
  ? num1  + sumAll((num1  + 1), num2)
  : num1  + num2;
}

Thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.