Skip to content

Commit 7d07f44

Browse files
committed
Completed Sprint 1/ Fix
1 parent 96d077b commit 7d07f44

2 files changed

Lines changed: 19 additions & 4 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+
const numbersOnly = list.filter(item => typeof item === 'number');
13+
const sorted = [...numbersOnly].sort((a, b) => a - b);
14+
15+
if (sorted.length === 0) {
16+
return null;
17+
} else if (sorted.length % 2 === 0) {
18+
const mid1 = sorted.length / 2 - 1;
19+
const mid2 = sorted.length / 2;
20+
const median = (sorted[mid1] + sorted[mid2]) / 2;
21+
return median;
22+
} else {
23+
const middleIndex = Math.floor(sorted.length / 2);
24+
const median = sorted[middleIndex];
25+
return median;
26+
}
1227
}
1328

1429
module.exports = calculateMedian;

Sprint-1/fix/median.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ describe("calculateMedian", () => {
2222
{ input: [4, 2, 1, 3], expected: 2.5 },
2323
{ input: [6, 1, 5, 3, 2, 4], expected: 3.5 },
2424
{ input: [110, 20, 0], expected: 20 },
25-
{ input: [6, -2, 2, 12, 14], expected: 6 },
25+
{ input: [6, -2, 2, 12, 14], expected: 6},
2626
].forEach(({ input, expected }) =>
2727
it(`returns the correct median for unsorted array [${input}]`, () => expect(calculateMedian(input)).toEqual(expected))
2828
);

0 commit comments

Comments
 (0)