Skip to content

Commit 4d87c5a

Browse files
committed
Merge branch 'coursework/sprint-1-fix' into coursework/sprint-1-data-groups
2 parents 96d077b + c4b663d commit 4d87c5a

1 file changed

Lines changed: 27 additions & 3 deletions

File tree

Sprint-1/fix/median.js

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,33 @@
66
// or 'list' has mixed values (the function is expected to sort only numbers).
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+
// Return null immediately if the input is not an array
10+
if (!Array.isArray(list)) {
11+
return null;
12+
}
13+
14+
// Keep only real numeric values
15+
const numbersOnly = list.filter(
16+
(item) => typeof item === "number" && !Number.isNaN(item)
17+
);
18+
19+
// Return null if the array contains no numbers
20+
if (numbersOnly.length === 0) {
21+
return null;
22+
}
23+
24+
// Create a sorted copy so the original input is not changed
25+
const sortedNumbers = [...numbersOnly].sort((a, b) => a - b);
26+
27+
const middleIndex = Math.floor(sortedNumbers.length / 2);
28+
29+
// For an even-length array, median is the average of the two middle values
30+
if (sortedNumbers.length % 2 === 0) {
31+
return (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2;
32+
}
33+
34+
// For an odd-length array, median is the middle value
35+
return sortedNumbers[middleIndex];
1236
}
1337

1438
module.exports = calculateMedian;

0 commit comments

Comments
 (0)