|
6 | 6 | // or contains values that aren't numbers (the function is expected to throw - see the tests). |
7 | 7 |
|
8 | 8 | 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; |
40 | 12 | } |
41 | 13 |
|
42 | 14 | 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