Skip to content
57 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Add math helpers, tests and checks1// Small helpers for numbers.
Merge #3: Add multiply to math.js2/** Returns the sum of a and b. */
Add math helpers, tests and checks3function add(a, b) {
4 return a + b;
5}
6
Merge #3: Add multiply to math.js7/** Returns the product of a and b. */
8function multiply(a, b) {
9 return a * b;
10}
11
Add mod function to math.js12/** Returns the non-negative remainder of a divided by b; throws RangeError when b is 0. */
13function mod(a, b) {
14 if (b === 0) {
15 throw new RangeError("mod by zero");
16 }
17 return ((a % b) + Math.abs(b)) % Math.abs(b);
18}
19
Catch up with main20/** Returns base raised to the whole-number exponent; throws a RangeError if exponent is negative. */
21function power(base, exponent) {
22 if (exponent < 0) {
23 throw new RangeError("exponent must not be negative");
24 }
25 let result = 1;
26 for (let i = 0; i < exponent; i++) {
27 result *= base;
28 }
29 return result;
30}
31
Catch up with main32/** Returns the average of numbers; throws a TypeError if the array is empty. */
33function mean(numbers) {
34 if (numbers.length === 0) {
35 throw new TypeError("numbers must not be empty");
36 }
37 return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
38}
39
40/** 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. */
41function median(numbers) {
42 if (numbers.length === 0) {
43 throw new TypeError("numbers must not be empty");
44 }
45 const sorted = [...numbers].sort((a, b) => a - b);
46 const mid = Math.floor(sorted.length / 2);
47 return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
48}
49
50/** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */
51function standard_deviation(numbers) {
52 const avg = mean(numbers);
53 const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length;
54 return Math.sqrt(variance);
55}
56
57module.exports = { add, multiply, mod, power, mean, median, standard_deviation };

This file's history is long; its oldest lines are credited to the oldest commit read.