|
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 | | - const middleIndex = Math.floor(list.length / 2); |
10 | | - const median = list.splice(middleIndex, 1)[0]; |
11 | | - return median; |
| 9 | + if (Array.isArray(list) === false) { |
| 10 | + throw new Error("calculateMedian requires an array of numbers"); |
| 11 | + } |
| 12 | + |
| 13 | + if (list === null || list === undefined) { |
| 14 | + throw new Error("calculateMedian requires an array of numbers"); |
| 15 | + } |
| 16 | + |
| 17 | + if (typeof list === "string" || typeof list === "number") { |
| 18 | + throw new Error("calculateMedian requires an array of numbers"); |
| 19 | + } |
| 20 | + |
| 21 | + if (list.length === 0) { |
| 22 | + throw new Error("calculateMedian requires a non-empty array"); |
| 23 | + } |
| 24 | + |
| 25 | + if (list.every((item) => typeof item === "string")) { |
| 26 | + throw new Error("calculateMedian requires an array of numbers"); |
| 27 | + } |
| 28 | + |
| 29 | + if (list.some((item) => typeof item === "string" || item === null || item === undefined)) { |
| 30 | + throw new Error("calculateMedian requires an array of numbers"); |
| 31 | + } |
| 32 | + |
| 33 | + const sortedList = [...list].sort((a, b) => a - b); |
| 34 | + |
| 35 | + if (sortedList.length % 2 === 0) { |
| 36 | + const evenMiddleIndex = Math.floor(sortedList.length / 2); |
| 37 | + const sumOfEvenMiddleIndex = |
| 38 | + sortedList.splice(evenMiddleIndex, 1)[0] + |
| 39 | + sortedList.splice(evenMiddleIndex - 1, 1)[0]; |
| 40 | + return sumOfEvenMiddleIndex / 2; |
| 41 | + } else { |
| 42 | + const oddMiddleIndex = Math.ceil(sortedList.length / 2); |
| 43 | + return sortedList.splice(oddMiddleIndex - 1, 1)[0]; |
| 44 | + } |
12 | 45 | } |
13 | 46 |
|
14 | 47 | module.exports = calculateMedian; |
0 commit comments