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
Advertisement
Answer
I made in this way:
const sumAll = function (x, y) { if (x > 0 && y > 0 && typeof x === 'number' && typeof y === 'number') { var valorx = x; var valory = y; var total = 0; if (x < y) { for (var i = valorx; i <= valory; i++) { total += i; } return total; } else if (x > y) { for (var i = valory; i <= valorx; i++) { total += i; } return total; } } else { return 'ERROR' } } module.exports = sumAll