Skip to content

Commit f7ce2f5

Browse files
committed
Refactor calculateMedian function to handle non-array inputs and mixed values
1 parent de6889c commit f7ce2f5

1 file changed

Lines changed: 18 additions & 3 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,24 @@
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)) {
10+
return null;
11+
}
12+
13+
const numbers = list.filter((item) => typeof item === "number");
14+
15+
if (numbers.length === 0) {
16+
return null;
17+
}
18+
19+
const sorted = [...numbers].sort((a, b) => a - b);
20+
const middleIndex = Math.floor(sorted.length / 2);
21+
22+
if (sorted.length % 2 === 0) {
23+
return (sorted[middleIndex - 1] + sorted[middleIndex]) / 2;
24+
} else {
25+
return sorted[middleIndex];
26+
}
1227
}
1328

1429
module.exports = calculateMedian;

0 commit comments

Comments
 (0)