Skip to content

Commit 7716249

Browse files
committed
wrote implemention for sum function to add integers and wrote multiple test cases for it to meet acceptance criteria
1 parent 0c123a4 commit 7716249

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

Sprint-1/implement/sum.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,22 @@
11
function sum(elements) {
2+
if (!Array.isArray(elements)) {
3+
return 0;
4+
}
5+
6+
// Filter only numeric values
7+
const numbers = elements.filter(function (item) {
8+
return typeof item === "number" && !isNaN(item);
9+
});
10+
11+
// If no numeric values, return 0
12+
if (numbers.length === 0) {
13+
return 0;
14+
}
15+
16+
// Add the numbers
17+
return numbers.reduce(function (total, value) {
18+
return total + value;
19+
}, 0);
220
}
321

422
module.exports = sum;

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 just one number, returns that number", () => {
24+
expect(sum([5])).toBe(5);
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 total sum", () => {
31+
expect(sum([-10, 20, -5])).toBe(5);
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/float numbers, returns the correct total sum", () => {
38+
expect(sum([3.14, 2.71, 1.41])).toBe(7.26);
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 containing non-number values, ignores non-numerical values and returns the sum of numerical elements", () => {
45+
expect(sum(['hey', 10, 'hi', 60, 10])).toBe(80);
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 the least surprising value", () => {
52+
expect(sum(['hey', 'hi', 'hello'])).toBe(0);
53+
});

0 commit comments

Comments
 (0)