sum([2, 3, 4, 5], 3) should equal 9. code example

Example 1: sum([2, 3, 4], 1) should equal 2.

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

sumAll([1, 4]);

Example 2: sum([2, 3, 4], 1) should equal 2.

function sum(arr, n) {

  // Only change code below this line

  if (n <= 0)// if n is less than or equals to 0{

    return 0 // should return zero

  } else {

    return sum(arr, n-1) + arr[n-1];

  }

  // Only change code above this line

}

sum([1],0);

Tags:

Misc Example