'The Odin Project - Fundamentals 4 Exercises - sumAll

I am stuck in the sumAll exercise from the Fundamentals 4 portion of the Odin Project. I managed to pass the test in which I need the result to be ‘ERROR’. However, I cannot figure out the correct code to pass the other tests. Where did I go wrong?

This is the exercise:

const sumAll = require(’./sumAll’)

describe(‘sumAll’, function() {
it(‘sums numbers within the range’, function() {
expect(sumAll(1, 4)).toEqual(10);
});
it(‘works with large numbers’, function() {
expect(sumAll(1, 4000)).toEqual(8002000);
});
it(‘works with larger number first’, function() {
expect(sumAll(123, 1)).toEqual(7626);
});
it(‘returns ERROR with negative numbers’, function() {
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
});
});

My code:

const sumAll = function(a, b) {
const arr = [];
if (a < b) {
while (a <= b) {
arr.push(a++);
}
} else if (b < a) {
while (b <= a) {
arr.push(b++);
}
} else {
arr.push(a);
}

if (a < 0 || b < 0) {
return “ERROR”;
} else if (typeof a !== NaN || typeof b !== NaN) {
return “ERROR”;
}
return arr.reduce((a, b) => a + b);
}

module.exports = sumAll


Solution 1:[1]

this how it work for me

const sumAll = function (startN, endN) {
//create variable to store total sum
  let sum = 0;

check if input parameter in number:

  if (typeof startN != "number" || typeof endN != "number") return "ERROR";

check if input numbers greter than 0:

  else if (startN < 0 || endN < 0) return "ERROR";

and last check is, if last number greater than the first number then initial number will be the last number otherwise start number will be the initial:

  else if (startN < endN) {
    for (i = startN; i <= endN; i++) {
      sum += i;
    }
  } else {
    for (i = endN; i <= startN; i++) {
      sum += i;
    }
  }

then return sum:

  return sum;
};

you can make all these in one check but this are more readable.

Solution 2:[2]

That's how i did it. Quite similar but i avoided using for loops.

const sumAll = function(n,m) {
if (n<0 || m<0 || typeof(m) !== 'number' || typeof(n) !== 'number'){
return 'ERROR'
}else {
if(n<m){
n1 = n
n2 = m 
}else{
    n1 = m
    n2 = n
}
return (n1+n2)*(n2/2)}
};

I first checked whether the input is valid, then decided the values of the two variables depending on which is bigger and finally calculated the sum.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Àbdirisak HD
Solution 2 lcelloh