Skip to content

Commit 816b104

Browse files
committed
Implement sum function and add full test coverage
1 parent bb247fd commit 816b104

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎Sprint-1/implement/sum.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
function sum(elements) {
2+
const numbers = elements.filter((item) => typeof item === "number");
3+
if (numbers.length === 0) {
4+
return 0;
5+
}
6+
return numbers.reduce((total, num) => total + num, 0);
27
}
38

49
module.exports = sum;

‎Sprint-1/implement/sum.test.js‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,42 @@ const sum = require("./sum.js");
1313
// Given an empty array
1414
// When passed to the sum function
1515
// Then it should return 0
16-
test.todo("given an empty array, returns 0")
16+
// test.todo("given an empty array, returns 0")
17+
test("given an empty array, returns 0", () => {
18+
expect(sum([])).toBe(0);
19+
});
1720

1821
// Given an array with just one number
1922
// When passed to the sum function
2023
// Then it should return that number
24+
test("given an array with one number, returns that number", () => {
25+
expect(sum([42])).toBe(42);
26+
});
2127

2228
// Given an array containing negative numbers
2329
// When passed to the sum function
2430
// Then it should still return the correct total sum
31+
test("given an array with negative numbers, returns the correct total", () => {
32+
expect(sum([-5, 10, -3])).toBe(2);
33+
});
2534

2635
// Given an array with decimal/float numbers
2736
// When passed to the sum function
2837
// Then it should return the correct total sum
38+
test("given an array with decimal numbers, returns the correct total", () => {
39+
expect(sum([1.5, 2.5, 3.1])).toBe(7.1);
40+
});
2941

3042
// Given an array containing non-number values
3143
// When passed to the sum function
3244
// Then it should ignore the non-numerical values and return the sum of the numerical elements
45+
test("given an array with non-number values, ignores them and returns the sum of numbers", () => {
46+
expect(sum(["hey", 10, "hi", 60, 10])).toBe(80);
47+
});
3348

3449
// Given an array with only non-number values
3550
// When passed to the sum function
3651
// Then it should return the least surprising value given how it behaves for all other inputs
52+
test("given an array with only non-number values, returns 0", () => {
53+
expect(sum(["a", null, undefined, "b"])).toBe(0);
54+
});

0 commit comments

Comments
 (0)