Skip to content

Commit fa57e04

Browse files
Refactor calculateMedian function to include input validation and correct median calculation
1 parent a8a23e3 commit fa57e04

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,23 @@
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+
if (list.length === 0) {
13+
throw new Error("calculateMedian requires a non-empty array");
14+
}
15+
if (!list.every((item) => typeof item === "number")) {
16+
throw new Error("calculateMedian requires an array of numbers");
17+
}
18+
19+
const sortedList = [...list].sort((a, b) => a - b);
20+
const middleIndex = Math.floor(sortedList.length / 2);
21+
22+
if (sortedList.length % 2 === 1) {
23+
return sortedList[middleIndex];
24+
}
25+
return (sortedList[middleIndex - 1] + sortedList[middleIndex]) / 2;
1226
}
1327

1428
module.exports = calculateMedian;

0 commit comments

Comments
 (0)