| 26 | 26 | | return result; |
| 27 | 27 | | } |
| 28 | 28 | | |
| 29 | | − | module.exports = { add, multiply, subtract, power }; |
| 29 | + | /** Returns the average of numbers; throws a TypeError if the array is empty. */ |
| 30 | + | function mean(numbers) { |
| 31 | + | if (numbers.length === 0) { |
| 32 | + | throw new TypeError("numbers must not be empty"); |
| 33 | + | } |
| 34 | + | return numbers.reduce((sum, n) => sum + n, 0) / numbers.length; |
| 35 | + | } |
| 36 | + | |
| 37 | + | /** Returns the middle value of numbers (the average of the two middle values when the length is even); throws a TypeError if the array is empty. */ |
| 38 | + | function median(numbers) { |
| 39 | + | if (numbers.length === 0) { |
| 40 | + | throw new TypeError("numbers must not be empty"); |
| 41 | + | } |
| 42 | + | const sorted = [...numbers].sort((a, b) => a - b); |
| 43 | + | const mid = Math.floor(sorted.length / 2); |
| 44 | + | return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]; |
| 45 | + | } |
| 46 | + | |
| 47 | + | /** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */ |
| 48 | + | function standard_deviation(numbers) { |
| 49 | + | const avg = mean(numbers); |
| 50 | + | const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length; |
| 51 | + | return Math.sqrt(variance); |
| 52 | + | } |
| 53 | + | |
| 54 | + | module.exports = { add, multiply, subtract, power, mean, median, standard_deviation }; |