Skip to content

Commit ca8c1ce

Browse files
committed
completed implementation of mean.js
1 parent d4189cd commit ca8c1ce

1 file changed

Lines changed: 36 additions & 3 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,42 @@
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) === false) {
10+
throw new Error("calculateMedian requires an array of numbers");
11+
}
12+
13+
if (list === null || list === undefined) {
14+
throw new Error("calculateMedian requires an array of numbers");
15+
}
16+
17+
if (typeof list === "string" || typeof list === "number") {
18+
throw new Error("calculateMedian requires an array of numbers");
19+
}
20+
21+
if (list.length === 0) {
22+
throw new Error("calculateMedian requires a non-empty array");
23+
}
24+
25+
if (list.every((item) => typeof item === "string")) {
26+
throw new Error("calculateMedian requires an array of numbers");
27+
}
28+
29+
if (list.some((item) => typeof item === "string" || item === null || item === undefined)) {
30+
throw new Error("calculateMedian requires an array of numbers");
31+
}
32+
33+
const sortedList = [...list].sort((a, b) => a - b);
34+
35+
if (sortedList.length % 2 === 0) {
36+
const evenMiddleIndex = Math.floor(sortedList.length / 2);
37+
const sumOfEvenMiddleIndex =
38+
sortedList.splice(evenMiddleIndex, 1)[0] +
39+
sortedList.splice(evenMiddleIndex - 1, 1)[0];
40+
return sumOfEvenMiddleIndex / 2;
41+
} else {
42+
const oddMiddleIndex = Math.ceil(sortedList.length / 2);
43+
return sortedList.splice(oddMiddleIndex - 1, 1)[0];
44+
}
1245
}
1346

1447
module.exports = calculateMedian;

0 commit comments

Comments
 (0)