| 1 | // Small helpers for numbers. |
| 2 | /** Returns the sum of a and b. */ |
| 3 | function add(a, b) { |
| 4 | return a + b; |
| 5 | } |
| 6 | |
| 7 | /** Returns the product of a and b. */ |
| 8 | function multiply(a, b) { |
| 9 | return a * b; |
| 10 | } |
| 11 | |
| 12 | /** Returns base raised to the whole-number exponent; throws a RangeError if exponent is negative. */ |
| 13 | function power(base, exponent) { |
| 14 | if (exponent < 0) { |
| 15 | throw new RangeError("exponent must not be negative"); |
| 16 | } |
| 17 | let result = 1; |
| 18 | for (let i = 0; i < exponent; i++) { |
| 19 | result *= base; |
| 20 | } |
| 21 | return result; |
| 22 | } |
| 23 | |
| 24 | /** Returns the average of numbers; throws a TypeError if the array is empty. */ |
| 25 | function mean(numbers) { |
| 26 | if (numbers.length === 0) { |
| 27 | throw new TypeError("numbers must not be empty"); |
| 28 | } |
| 29 | return numbers.reduce((sum, n) => sum + n, 0) / numbers.length; |
| 30 | } |
| 31 | |
| 32 | /** 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. */ |
| 33 | function median(numbers) { |
| 34 | if (numbers.length === 0) { |
| 35 | throw new TypeError("numbers must not be empty"); |
| 36 | } |
| 37 | const sorted = [...numbers].sort((a, b) => a - b); |
| 38 | const mid = Math.floor(sorted.length / 2); |
| 39 | return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]; |
| 40 | } |
| 41 | |
| 42 | /** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */ |
| 43 | function standard_deviation(numbers) { |
| 44 | const avg = mean(numbers); |
| 45 | const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length; |
| 46 | return Math.sqrt(variance); |
| 47 | } |
| 48 | |
| 49 | module.exports = { add, multiply, power, mean, median, standard_deviation }; |