Recursive Trinary... maybe just use an if .. else?

I’m probably trying to be too clever for my own good but I normally find that is what really tests my understanding.
I’ve returned using trinaries before but in this case I’m trying to do it recursively too.
Obviously I’m doing something pretty fundamentally wrong as vscode is giving me an error before I even run it. What stupid thing am I doing or not understanding?

  **Your code so far**

function sumAll(arr) {
return arr[0] === arr[1] ? arr[0] :
  arr[0] > arr[1] ? arr[0] + sumAll([ arr[0]-1, arr[1]]):
  arr[1] > arr[0] ? arr[1] + sumAll([ arr[0], arr[1]-1])
} // ignore the line count, THIS IS THE BRACE IN THE ERROR

sumAll([1, 4]);

Challenge: Sum All Numbers in a Range

Link to the challenge:

Hello there,

It looks like you are just missing (essentially) an else clause:

The way I look at it

const cond_1 = arr[0] === arr[1];
const clause_1 = arr[0];
const cond_2 = arr[0] > arr[1];
const clause_2 = arr[0] + sumAll([ arr[0]-1, arr[1]]);
const cond_3 = arr[1] > arr[0];
const clause_3 = arr[1] + sumAll([ arr[0], arr[1]-1]);
return cond_1 ? clause_1 : cond_2 ? clause_2 : cond_3 ? clause_3;
// There should be a final clause

Hope this helps/is clear.

1 Like

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