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:
JavaScript
x
23
23
1
const sumAll = require(’./sumAll’)
2
3
describe(‘sumAll’, function() {
4
it(‘sums numbers within the range’, function() {
5
expect(sumAll(1, 4)).toEqual(10);
6
});
7
it(‘works with large numbers’, function() {
8
expect(sumAll(1, 4000)).toEqual(8002000);
9
});
10
it(‘works with larger number first’, function() {
11
expect(sumAll(123, 1)).toEqual(7626);
12
});
13
it(‘returns ERROR with negative numbers’, function() {
14
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
15
});
16
it(‘returns ERROR with non-number parameters’, function() {
17
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
18
});
19
it(‘returns ERROR with non-number parameters’, function() {
20
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
21
});
22
});
23
My code:
JavaScript
1
24
24
1
const sumAll = function(a, b) {
2
const arr = [];
3
if (a < b) {
4
while (a <= b) {
5
arr.push(a++);
6
}
7
} else if (b < a) {
8
while (b <= a) {
9
arr.push(b++);
10
}
11
} else {
12
arr.push(a);
13
}
14
15
if (a < 0 || b < 0) {
16
return “ERROR”;
17
} else if (typeof a !== NaN || typeof b !== NaN) {
18
return “ERROR”;
19
}
20
return arr.reduce((a, b) => a + b);
21
}
22
23
module.exports = sumAll
24
Advertisement
Answer
I made in this way:
JavaScript
1
23
23
1
const sumAll = function (x, y) {
2
if (x > 0 && y > 0 && typeof x === 'number' && typeof y === 'number') {
3
var valorx = x;
4
var valory = y;
5
var total = 0;
6
if (x < y) {
7
for (var i = valorx; i <= valory; i++) {
8
total += i;
9
}
10
return total;
11
} else if (x > y) {
12
for (var i = valory; i <= valorx; i++) {
13
total += i;
14
}
15
return total;
16
}
17
} else {
18
return 'ERROR'
19
}
20
}
21
22
module.exports = sumAll
23