Skip to content

Commit 8176dba

Browse files
committed
i have done tasks under fix in Sprint 1 exercise.
1 parent de6889c commit 8176dba

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
1-
// Fix this implementation
2-
// Start by running the tests for this function
3-
// If you're in the Sprint-1 directory, you can run `npm test -- fix` to run the tests in the fix directory
1+
function calculateMedian(list) {
2+
const numbers = [];
3+
for (const x of list) {
4+
if (typeof x === "number") {
5+
numbers.push(x);
6+
}
7+
}
8+
if (numbers.length === 0 || list.length === 0) {
9+
return null;
10+
}
411

5-
// Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null)
6-
// or 'list' has mixed values (the function is expected to sort only numbers).
12+
numbers.sort((a, b) => a - b);
13+
const middleIndex = Math.floor(numbers.length / 2);
714

8-
function calculateMedian(list) {
9-
const middleIndex = Math.floor(list.length / 2);
10-
const median = list.splice(middleIndex, 1)[0];
15+
if (numbers.length % 2 === 0) {
16+
const left = numbers[middleIndex - 1];
17+
const right = numbers[middleIndex];
18+
return (left + right) / 2;
19+
}
20+
21+
const median = numbers[middleIndex];
1122
return median;
1223
}
1324

0 commit comments

Comments
 (0)