Skip to content

Commit d5f3e06

Browse files
committed
Implemented calculateMedian function
1 parent 96d077b commit d5f3e06

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

Sprint-1/fix/median.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,28 @@
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+
10+
// first of all, checking if 'list' is an array
11+
if (Array.isArray(list)) {
12+
13+
const filteredArr = list.filter(x => typeof x === 'number');
14+
15+
if (filteredArr.length < 2) {
16+
return null;
17+
}
18+
19+
// using 'spread operator' copies the array without mutating it
20+
const sortedList = [...filteredArr].sort((a, b) => a - b);
21+
22+
const middleIndex = Math.floor(sortedList.length / 2);
23+
24+
if (sortedList.length % 2 === 0) {
25+
return (sortedList[middleIndex - 1] + sortedList[middleIndex]) / 2;
26+
} else {
27+
return sortedList[middleIndex]
28+
}
29+
}
30+
return null;
1231
}
1332

1433
module.exports = calculateMedian;

0 commit comments

Comments
 (0)