Help with Sum All Numbers in a Range

Tell us what’s happening:
I think this should work instead it brings “max callstack reach” whats wrong ?

Your code so far


function sumAll(arr) {
  return arr.map(a => a * 1).sort((a,b) => b-a).reduce( function lit(a, b){
    if (a == b) {
      return b;
    }
    return a + lit(a - 1);
  });
}

var result = sumAll([1, 5]);
console.log(result);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range

You are running a recursion on the callback function of reduce ? Could you please explain it a bit on why and how you envision this approach to work ?

Also, while your recursion function requires 2 arguments, on every call it is being supplied only one a-1, the recursion function has no escape hatch…

i expect the recursion to escape with if(a == b) since b is the minimum after it as undergo sort(). Here a is higher number while b is the lower. Maybe not the best approach ?

but you are passing the recursion function only the value for a, and not a and b, I’m not sure if that would still work after you change that, but right now it is not escaping the recursion function hence the ‘max callstack’ error, the stack operates with last in first out and has no escape since b is perpetually undefined.
Personally, I wouldn’t say it is the best approach as it is not very readable as a standard loop would be, but certainly interesting to experiment with recursion.

1 Like

@dareedyone, consider a standalone recursive function that adds the numbers in-between a given array that is sorted-descending (as you have) but without using reduce, it would look something like this

function addRecursion([a, b]){
    if (a == b) {
      return a;
    }
    return a + addRecursion([a - 1,b]);
  }
addRecursion([4,1]) // 10

if you can try to imagine how the stack executes
4 + (3 + (2 + 1))

meaning, the values in the most inner parentheses are executed first (last in) and the outermost is executed last (first in) .
Now, when you introduce reduce to the given array (which is overkill at this point other than for a mental exercise) the callback will act upon each element of the array being reduced, but it’s arguments would need to be aligned with that of the standalone function above, could you think of ways to do that ?

1 Like

I could try…:smile: