Skip to content

Commit 1768fb3

Browse files
committed
fixing median.js
1 parent c5ca9b3 commit 1768fb3

1 file changed

Lines changed: 3 additions & 45 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 3 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -6,51 +6,9 @@
66
// or contains values that aren't numbers (the function is expected to throw - see the tests).
77

88
function calculateMedian(list) {
9-
// Check that the input is an array
10-
if (!Array.isArray(list)) {
11-
throw new Error("calculateMedian requires an array of numbers");
12-
}
13-
14-
// Check that the array is not empty
15-
if (list.length === 0) {
16-
throw new Error("calculateMedian requires a non-empty array");
17-
}
18-
19-
// Check that every item is a number
20-
if (!list.every((item) => typeof item === "number" && !isNaN(item))) {
21-
throw new Error("calculateMedian requires an array of numbers");
22-
}
23-
24-
// Make a copy so we don't modify the original array
25-
const sortedList = [...list];
26-
27-
// Sort numbers from smallest to largest
28-
sortedList.sort((a, b) => a - b);
29-
30-
// Find the middle index
31-
const middleIndex = Math.floor(sortedList.length / 2);
32-
33-
// Odd number of elements
34-
if (sortedList.length % 2 === 1) {
35-
return sortedList[middleIndex];
36-
}
37-
38-
// Even number of elements
39-
return (sortedList[middleIndex - 1] + sortedList[middleIndex]) / 2;
9+
const middleIndex = Math.floor(list.length / 2);
10+
const median = list.splice(middleIndex, 1)[0];
11+
return median;
4012
}
4113

4214
module.exports = calculateMedian;
43-
44-
// function calculateMedian(list) {
45-
// if (list.length === 0) return null;
46-
// list = list.filter((item) => typeof item === "number" && !isNaN(item));
47-
// list.sort((a, b) => a - b);
48-
// const middleIndex = Math.floor(list.length / 2);
49-
// if (list.length % 2 === 1) {
50-
// return list[middleIndex]; //odd number if elements
51-
// }
52-
53-
// return (list[middleIndex - 1] + list[middleIndex]) / 2;
54-
// }
55-
56-
// module.exports = calculateMedian;

0 commit comments

Comments
 (0)