Skip to content

Commit 22649fc

Browse files
committed
fix median function to handle unsorted arrays, non-numeric values and edge cases
1 parent de6889c commit 22649fc

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
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+
if (!Array.isArray(list)) return null;
10+
const numbers = list.filter(n => typeof n === "number");
11+
if (numbers.length === 0) return null;
12+
const sorted = [...numbers].sort((a, b) => a - b);
13+
const mid = Math.floor(sorted.length / 2);
14+
return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
1215
}
1316

1417
module.exports = calculateMedian;

0 commit comments

Comments
 (0)