Skip to content

Commit a5d9c95

Browse files
committed
median.js completed
1 parent d4189cd commit a5d9c95

1 file changed

Lines changed: 31 additions & 3 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,37 @@
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+
16+
for (item of list) {
17+
if (typeof item === "string") {
18+
throw new Error("calculateMedian requires an array of numbers");
19+
}
20+
if (item === null) {
21+
throw new Error("calculateMedian requires an array of numbers");
22+
}
23+
if (list.includes(undefined)) {
24+
throw new Error("calculateMedian requires an array of numbers");
25+
}
26+
}
27+
28+
const sorted = list.toSorted((a, b) => a - b);
29+
const oddNum = list.length % 2 === 1;
30+
31+
if (oddNum) {
32+
const middleIndex = Math.floor(list.length / 2);
33+
return sorted[middleIndex];
34+
} else {
35+
const middleIndex = Math.floor(list.length / 2);
36+
const middle = middleIndex - 1;
37+
const median = (sorted[middleIndex] + sorted[middle]) / 2;
38+
return median;
39+
}
1240
}
1341

1442
module.exports = calculateMedian;

0 commit comments

Comments
 (0)