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: