Skip to content

Commit 6dcfc89

Browse files
committed
Fix calculateMedian: sort, even length, no mutation, validation
1 parent d4189cd commit 6dcfc89

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,28 @@
66
// or contains values that aren't numbers (the function is expected to throw - see the tests).
77

88
function calculateMedian(list) {
9-
const middleIndex = Math.floor(list.length / 2);
10-
const median = list.splice(middleIndex, 1)[0];
11-
return median;
9+
if (!Array.isArray(list)) {
10+
throw new Error("calculateMedian requires an array of numbers");
11+
}
12+
13+
if (list.length === 0) {
14+
throw new Error("calculateMedian requires a non-empty array");
15+
}
16+
17+
for (const item of list) {
18+
if (typeof item !== "number") {
19+
throw new Error("calculateMedian requires an array of numbers");
20+
}
21+
}
22+
23+
const sorted = list.slice().sort((a, b) => a - b);
24+
const middleIndex = Math.floor(sorted.length / 2);
25+
26+
if (sorted.length % 2 === 0) {
27+
return (sorted[middleIndex - 1] + sorted[middleIndex]) / 2;
28+
}
29+
30+
return sorted[middleIndex];
1231
}
1332

1433
module.exports = calculateMedian;

0 commit comments

Comments
 (0)