Skip to content

Commit a8a23e3

Browse files
Refactor describeMedian function to improve error handling for empty and non-array inputs
1 parent 67e1d52 commit a8a23e3

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

‎Sprint-1/implement/describe-median.js‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
// Don't change this function.
22
function calculateMedian(list) {
3-
if (!Array.isArray(list)) {
4-
throw new Error("calculateMedian requires an array of numbers");
5-
}
63
if (list.length === 0) {
74
throw new Error("calculateMedian requires a non-empty array");
85
}
6+
7+
if (!Array.isArray(list)) {
8+
throw new Error("calculateMedian requires an array of numbers");
9+
}
10+
911
for (const item of list) {
1012
if (typeof item !== "number") {
1113
throw new Error("calculateMedian requires an array of numbers");
@@ -20,6 +22,18 @@ function calculateMedian(list) {
2022
}
2123

2224
// Implement this function. See describe-median.test.js for the acceptance criteria.
23-
function describeMedian(list) {}
25+
function describeMedian(list) {
26+
try {
27+
return "The median is " + calculateMedian(list);
28+
} catch {
29+
if (list.length === 0) {
30+
return "Could not calculate a median: calculateMedian requires a non-empty array";
31+
}
32+
33+
if (!Array.isArray(list)) {
34+
return "Could not calculate a median: calculateMedian requires an array of numbers";
35+
}
36+
}
37+
}
2438

2539
module.exports = describeMedian;

0 commit comments

Comments
 (0)