Skip to content

Commit 53fa90f

Browse files
author
Pretty Taruvinga
committed
implement correct median calculation
1 parent 96d077b commit 53fa90f

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

Sprint-1/fix/median.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,21 @@
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+
// Filter out non-numeric values and sort the remaining numbers
10+
const numbers = list
11+
.filter((x) => typeof x === "number" && !isNaN(x))
12+
.sort((a, b) => a - b);
13+
14+
if (numbers.length === 0) {
15+
return null;
16+
}
17+
18+
const mid = Math.floor(numbers.length / 2);
19+
if (numbers.length % 2 === 0) {
20+
return (numbers[mid - 1] + numbers[mid]) / 2;
21+
} else {
22+
return numbers[mid];
23+
}
1224
}
1325

1426
module.exports = calculateMedian;

0 commit comments

Comments
 (0)