Skip to content
54 linesCodeBlameRaw
1// Small helpers for numbers.
2/** Returns the sum of a and b. */
3function add(a, b) {
4 return a + b;
5}
6
7/** Returns a minus b. */
8function subtract(a, b) {
9 return a - b;
10}
11
12/** Returns the product of a and b. */
13function multiply(a, b) {
14 return a * b;
15}
16
17/** Returns base raised to the whole-number exponent; throws a RangeError if exponent is negative. */
18function power(base, exponent) {
19 if (exponent < 0) {
20 throw new RangeError("exponent must not be negative");
21 }
22 let result = 1;
23 for (let i = 0; i < exponent; i++) {
24 result *= base;
25 }
26 return result;
27}
28
29/** Returns the average of numbers; throws a TypeError if the array is empty. */
30function 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. */
38function 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. */
48function 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
54module.exports = { add, subtract, multiply, power, mean, median, standard_deviation };