Skip to content

Commit 8e213b2

Browse files
committed
Implement sum with tests
1 parent 553bc80 commit 8e213b2

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

‎Sprint-1/implement/sum.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,19 @@
11
function sum(elements) {
2+
if (!Array.isArray(elements)) {
3+
throw new Error("sum requires an array of numbers");
4+
}
5+
6+
for (const item of elements) {
7+
if (typeof item !== "number") {
8+
throw new Error("sum requires an array of numbers");
9+
}
10+
}
11+
12+
let total = 0;
13+
for (const item of elements) {
14+
total += item;
15+
}
16+
return total;
217
}
318

419
module.exports = sum;

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

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,46 @@ 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, should return 0", () => {
17+
expect(sum([])).toEqual(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, should return that number", () => {
24+
expect(sum([10])).toEqual(10);
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, should still return the correct total sum", () => {
31+
expect(sum([-3, -7, -2])).toEqual(-12);
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, should return the correct total sum", () => {
38+
expect(sum([1.3, 2.7, 3.5])).toEqual(7.5);
39+
});
2940

3041
// Given an array containing a value that isn't a number
3142
// When passed to the sum function
3243
// Then it should throw Error("sum requires an array of numbers")
44+
test("Throws an error when an array containing a value that isn't a number", () => {
45+
expect(() => sum([15, "car", 11])).toThrow(
46+
new Error("sum requires an array of numbers")
47+
);
48+
});
3349

3450
// Given something that isn't an array at all, such as "hey", 42 or no argument
3551
// When passed to the sum function
3652
// Then it should throw Error("sum requires an array of numbers")
53+
test("Throws an error when given something that isn't an array at all", () => {
54+
expect(() => sum("string")).toThrow(
55+
new Error("sum requires an array of numbers")
56+
);
57+
});
58+

0 commit comments

Comments
 (0)