Skip to content

Commit 73ac1d7

Browse files
improved readability and comments added
1 parent 7f0d8f5 commit 73ac1d7

1 file changed

Lines changed: 18 additions & 13 deletions

File tree

Sprint-1/fix/median.js

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,25 @@
66
// or 'list' has mixed values (the function is expected to sort only numbers).
77

88
function calculateMedian(list) {
9-
if (Array.isArray(list)) {
10-
let newList = list.filter(item => typeof item === "number");
11-
newList = newList.sort(function (a, b) {
12-
return a - b;
13-
});
14-
if (newList.length > 0){
15-
const middleIndex = Math.floor(newList.length / 2);
16-
const median = newList[middleIndex]
17-
if (newList.length % 2 !== 0) {
18-
return median;
9+
// if list is not an array, stop the function and return null
10+
if (!Array.isArray(list)) {
11+
return null;
12+
}
13+
14+
// the list is filtered to get only the numbers, then sorted in ascending order
15+
let newList = list.filter(item => Number.isFinite(item));
16+
newList = newList.sort(function (a, b) { return a - b });
17+
18+
// here we check if the list is empty, if not we calculate the median
19+
if (newList.length > 0){
20+
const middleIndex = Math.floor( newList.length / 2);
21+
const median = newList[middleIndex]
22+
if ( newList.length % 2 !== 0) {
23+
return median;
1924
}
20-
else return (newList[middleIndex - 1] + median) / 2}
21-
else return null;}
22-
else return null;
25+
return (newList[middleIndex - 1] + median) / 2;
26+
}
27+
return null;
2328
}
2429

2530
module.exports = calculateMedian;

0 commit comments

Comments
 (0)