Skip to content

Commit 8d1cad5

Browse files
committed
Fix function and tests
1 parent aed6d3a commit 8d1cad5

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

Sprint-1/implement/sum.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
11
function sum(elements) {
2+
let total = 0;
3+
for (const el of elements) {
4+
if (typeof el === "number") {
5+
total += el;
6+
}
7+
}
8+
return total;
29
}
3-
410
module.exports = sum;
11+

Sprint-1/implement/sum.test.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,41 @@ 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("given an empty array, returns 0", () => {
17+
expect(sum([])).toBe(0);
18+
});
1719

1820
// Given an array with just one number
1921
// When passed to the sum function
2022
// Then it should return that number
23+
test("given an array with one number, returns that number", () => {
24+
expect(sum([7])).toBe(7);
25+
});
2126

2227
// Given an array containing negative numbers
2328
// When passed to the sum function
2429
// Then it should still return the correct total sum
30+
test("given an array containing negative numbers, returns the correct sum", () => {
31+
expect(sum([10, -5, 3, -2])).toBe(6);
32+
});
2533

2634
// Given an array with decimal/float numbers
2735
// When passed to the sum function
2836
// Then it should return the correct total sum
37+
test("given an array with decimal numbers, returns the correct sum", () => {
38+
expect(sum([1.2, 3.5, 2.3])).toBe(7.0);
39+
});
2940

3041
// Given an array containing non-number values
3142
// When passed to the sum function
3243
// Then it should ignore the non-numerical values and return the sum of the numerical elements
44+
test("given an array with non-number values, returns the sum of numerical elements only", () => {
45+
expect(sum([10, "hi", 5, null, 3, "hello"])).toBe(18);
46+
});
3347

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

0 commit comments

Comments
 (0)