Skip to content

Commit 0b63649

Browse files
committed
implement sum function and tests
1 parent de6889c commit 0b63649

2 files changed

Lines changed: 19 additions & 16 deletions

File tree

‎Sprint-1/implement/sum.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
function sum(elements) {
2+
return elements.filter(n => typeof n === "number").reduce((acc, n) => acc + n, 0);
23
}
34

45
module.exports = sum;

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

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,26 @@ 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([])).toEqual(0);
18+
});
1719

18-
// Given an array with just one number
19-
// When passed to the sum function
20-
// Then it should return that number
20+
test("given an array with just one number, returns that number", () => {
21+
expect(sum([42])).toEqual(42);
22+
});
2123

22-
// Given an array containing negative numbers
23-
// When passed to the sum function
24-
// Then it should still return the correct total sum
24+
test("given an array containing negative numbers, returns the correct total", () => {
25+
expect(sum([10, -5, 3])).toEqual(8);
26+
});
2527

26-
// Given an array with decimal/float numbers
27-
// When passed to the sum function
28-
// Then it should return the correct total sum
28+
test("given an array with decimal numbers, returns the correct total", () => {
29+
expect(sum([1.5, 2.5])).toEqual(4);
30+
});
2931

30-
// Given an array containing non-number values
31-
// When passed to the sum function
32-
// Then it should ignore the non-numerical values and return the sum of the numerical elements
32+
test("given an array containing non-number values, ignores them and sums the rest", () => {
33+
expect(sum(["hey", 10, "hi", 60, 10])).toEqual(80);
34+
});
3335

34-
// Given an array with only non-number values
35-
// When passed to the sum function
36-
// Then it should return the least surprising value given how it behaves for all other inputs
36+
test("given an array with only non-number values, returns 0", () => {
37+
expect(sum(["a", "b"])).toEqual(0);
38+
});

0 commit comments

Comments
 (0)