Skip to content

Commit d5a2099

Browse files
committed
fixed function to test cases
1 parent de6889c commit d5a2099

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,29 @@
55
// Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null)
66
// or 'list' has mixed values (the function is expected to sort only numbers).
77

8-
function calculateMedian(list) {
8+
/*function calculateMedian(list) {
99
const middleIndex = Math.floor(list.length / 2);
1010
const median = list.splice(middleIndex, 1)[0];
1111
return median;
12+
}*/
13+
function calculateMedian(list){
14+
if(!Array.isArray(list)){
15+
return null;
16+
}
17+
const num = [];
18+
for(let i = 0; i < list.length ; i++){
19+
if (typeof list[i] === "number"){
20+
num.push(list[i]);
21+
}
22+
}
23+
if (num.length === 0){
24+
return null;
25+
}
26+
num.sort((a, b) => a - b);
27+
const middleIndex = Math.floor(num.length / 2);
28+
if (num.length % 2 === 1){
29+
return num[middleIndex];
30+
}
31+
return (num[middleIndex-1] + num[middleIndex])/2;
1232
}
13-
1433
module.exports = calculateMedian;

0 commit comments

Comments
 (0)