Skip to content
54 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
Add subtract to math.js7/** Returns a minus b. */
8function subtract(a, b) {
9 return a - b;
10}
11
Merge #3: Add multiply to math.js12/** Returns the product of a and b. */
13function multiply(a, b) {
14 return a * b;
15}
16
Add power function to math.js17/** 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
Add mean, median, and standard_deviation to math.js29/** 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
Export subtract from math.js54module.exports = { add, subtract, multiply, power, mean, median, standard_deviation };

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