Skip to content

Commit 97d433c

Browse files
committed
Sum numbers in an array
1 parent 0f21769 commit 97d433c

2 files changed

Lines changed: 28 additions & 3 deletions

File tree

‎Sprint-1/implement/sum.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
function sum(elements) {
2+
// Filtering out non-numeric values
3+
const numericElements = elements.filter(element => typeof element === 'number' && !isNaN(element));
4+
5+
// If there are no numeric values, return 0
6+
if (numericElements.length === 0) {
7+
return 0;
8+
}
9+
10+
// Using reduce to calculate the sum of the numeric elements
11+
return numericElements.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
212
}
313

414
module.exports = sum;

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

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,39 @@ 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
21-
23+
test("given an array with just one number, returns that number", () => {
24+
expect(sum([5])).toBe(5);
25+
});
2226
// Given an array containing negative numbers
2327
// When passed to the sum function
2428
// Then it should still return the correct total sum
29+
test("given an array containing negative numbers, returns the correct total sum", () => {
30+
expect(sum([-10, -20, -30])).toBe(-60);
31+
});
2532

2633
// Given an array with decimal/float numbers
2734
// When passed to the sum function
2835
// Then it should return the correct total sum
29-
36+
test("given an array with decimal/float numbers, returns the correct total sum", () => {
37+
expect(sum([1.5, 2.5, 3.5])).toBe(7.5);
38+
});
3039
// Given an array containing non-number values
3140
// When passed to the sum function
3241
// Then it should ignore the non-numerical values and return the sum of the numerical elements
42+
test("given an array containing non-number values, ignores the non-numerical values and returns the sum of the numerical elements", () => {
43+
expect(sum(['hey', 10, 'hi', 60, 10])).toBe(80);
44+
});
3345

3446
// Given an array with only non-number values
3547
// When passed to the sum function
3648
// Then it should return the least surprising value given how it behaves for all other inputs
49+
test("given an array with only non-number values, returns the least surprising value given how it behaves for all other inputs", () => {
50+
expect(sum(['hello', 'world'])).toBe(0);
51+
});

0 commit comments

Comments
 (0)