Skip to content
70 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
Merge main into clamp branch12/** Returns a minus b. */
13function subtract(a, b) {
14 return a - b;
15}
16
Catch up with main17/** Returns a divided by b; throws a RangeError when b is 0. */
18function divide(a, b) {
19 if (b === 0) {
20 throw new RangeError("Division by zero");
21 }
22 return a / b;
23}
24
Add power function to math.js25/** Returns base raised to the whole-number exponent; throws a RangeError if exponent is negative. */
26function power(base, exponent) {
27 if (exponent < 0) {
28 throw new RangeError("exponent must not be negative");
29 }
30 let result = 1;
31 for (let i = 0; i < exponent; i++) {
32 result *= base;
33 }
34 return result;
35}
36
Add mean, median, and standard_deviation to math.js37/** Returns the average of numbers; throws a TypeError if the array is empty. */
38function mean(numbers) {
39 if (numbers.length === 0) {
40 throw new TypeError("numbers must not be empty");
41 }
42 return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
43}
44
45/** 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. */
46function median(numbers) {
47 if (numbers.length === 0) {
48 throw new TypeError("numbers must not be empty");
49 }
50 const sorted = [...numbers].sort((a, b) => a - b);
51 const mid = Math.floor(sorted.length / 2);
52 return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
53}
54
55/** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */
56function standard_deviation(numbers) {
57 const avg = mean(numbers);
58 const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length;
59 return Math.sqrt(variance);
60}
61
Add clamp function to math.js62/** Returns value limited to the range [min, max]; throws a RangeError if min is greater than max. */
63function clamp(value, min, max) {
64 if (min > max) {
65 throw new RangeError("min must not be greater than max");
66 }
67 return Math.min(Math.max(value, min), max);
68}
69
Catch up with main70module.exports = { add, multiply, subtract, divide, power, mean, median, standard_deviation, clamp };

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