Skip to content

Commit 08758cb

Browse files
committed
fixed sum function and wrote tests
1 parent 868c5b9 commit 08758cb

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

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+
3+
// const filteredArr = elements.filter(x => typeof x === 'number');
4+
// return filteredArr.reduce((a, b) => a + b, 0);
5+
6+
return elements.filter(x => typeof x === 'number').reduce((a, b) => a + b, 0);
27
}
38

49
module.exports = sum;

Sprint-1/implement/sum.test.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,49 @@ 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+
17+
test("return 0 for an empty array", () => {
18+
expect(sum([])).toEqual(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
2124

25+
test("given an array with just one number, return that number", () => {
26+
expect(sum([3])).toEqual(3);
27+
expect(sum([-3])).toEqual(-3);
28+
expect(sum([0])).toEqual(0);
29+
})
30+
2231
// Given an array containing negative numbers
2332
// When passed to the sum function
2433
// Then it should still return the correct total sum
2534

35+
test("return the correct total when passed negative numbers", () => {
36+
expect(sum([-3, -6, -1])).toEqual(-10);
37+
})
38+
2639
// Given an array with decimal/float numbers
2740
// When passed to the sum function
2841
// Then it should return the correct total sum
42+
test("decimal number arrays", () => {
43+
expect(sum([0.2, 0.4, 0.2])).toEqual(0.8);
44+
})
2945

3046
// Given an array containing non-number values
3147
// When passed to the sum function
3248
// Then it should ignore the non-numerical values and return the sum of the numerical elements
3349

50+
test("an array with non-numbers", () => {
51+
expect(sum([2, "Blue", 3, "Black", "Green"])).toEqual(5);
52+
})
53+
3454
// Given an array with only non-number values
3555
// When passed to the sum function
3656
// Then it should return the least surprising value given how it behaves for all other inputs
57+
58+
test("an array with non-number values only", () => {
59+
expect(sum([true, false, "Black"])).toEqual(0);
60+
expect(sum([undefined, null, "Black"])).toEqual(0);
61+
})

0 commit comments

Comments
 (0)