Skip to content

Commit c01c0bc

Browse files
committed
Implement sum function to calculate the total of numeric values in an array, handling empty arrays and non-array inputs.
1 parent 065f1e6 commit c01c0bc

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

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 null;
4+
}
5+
// Check if array is empty
6+
if (elements.length === 0) {
7+
return 0;
8+
}
9+
// Filter only numeric values
10+
const numericElements = elements.filter((item) => typeof item === "number");
11+
if (numericElements.length === 0) {
12+
return -Infinity;
13+
}
14+
// Calculate the sum of numeric values
15+
let total = 0;
16+
for (let i = 0; i < numericElements.length; i++) {
17+
total += numericElements[i];
18+
}
19+
return total;
220
}
321

422
module.exports = sum;

0 commit comments

Comments
 (0)