Sum All javascript exercise


#1

Hello Everyone

Im currently doing the SumAll test exercise for javascript.
My code passes tests 1 and 2, but then fails the rest.
I understand why its failing, but for the life of me have no idea how to fix it.
Any advice would be much appreciated.

Tests

var 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);
  });
  xit('works with larger number first', function() {
    expect(sumAll(123, 1)).toEqual(7626);
  });
  xit('returns ERROR with negative numbers', function() {
    expect(sumAll(-10, 4)).toEqual('ERROR');
  });
  xit('returns ERROR with non-number parameters', function() {
    expect(sumAll(10, "90")).toEqual('ERROR');
  });
  xit('returns ERROR with non-number parameters', function() {
    expect(sumAll(10, [90, 1])).toEqual('ERROR');
  });
});

My Code

var sumAll = function(x,y) {
  var list = [];
  for (var i = x; i <= y; i++) {list.push(i);}
  var sum = list.reduce((acc, list) => acc + list);
  return(sum);
}

module.exports = sumAll

#2

all you really need to add here is a couple of checks for the parameters before you do the list stuff… something like (for example):

if (y > x) {
   // do stuff
}

i can give you more hints if you like… but see if that gets you anywhere.


#3

Hey @codyloyd

I have tried using an if else if else statement, but then I keep getting undefined ?


#4

Can we see your code @RDB931 where you use if / else?


#5

For the 3rd test, the problem is the order that the values are being passed - sumAll(x,y) or to clarify sumAll(bigNum,smallNum)

In for (var i = x; i <= y; i++) i is never going to be less than the value of y.

Could you re-order the values being passed?