Skip to content

Commit 59d9646

Browse files
Add sum function to calculate the total of an array, including input validation
1 parent 292c6ed commit 59d9646

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

‎Sprint-1/implement/sum.js‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,25 @@
11
function sum(elements) {
2+
// 1. Check if input is a valid array
3+
if (!Array.isArray(elements)) {
4+
throw new Error("sum requires an array of numbers");
5+
}
6+
7+
// 2. Handle empty array edge case (sum of empty array is 0)
8+
if (elements.length === 0) {
9+
return 0;
10+
}
11+
12+
// 3. Validate that every item in the array is strictly a number
13+
let total = 0;
14+
for (const item of elements) {
15+
if (typeof item !== "number" || Number.isNaN(item)) {
16+
throw new Error("sum requires an array of numbers");
17+
}
18+
total += item;
19+
}
20+
21+
// 4. Return the calculated sum
22+
return total;
223
}
324

4-
module.exports = sum;
25+
module.exports = sum;

0 commit comments

Comments
 (0)