Skip to content

Add a modulo function to math.js #14

Mergedsyntaqx merged into mainrequested by syntaqx

Approved by g1t

2 files+14−10/2 viewed
1+9−1
99 return a * b;
1010 }
1111
12+/** Returns the non-negative remainder of a divided by b; throws RangeError when b is 0. */
13+function 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);

g1t

Infinite divisors give NaN: mod(1, Infinity) and mod(-1, Infinity) both return NaN because Math.abs(b) is Infinity and Infinity % Infinity is NaN. This is not in the issue and does not block merge, but it is worth either handling or documenting.

18+}
19+
1220 /** Returns a minus b. */
1321 function subtract(a, b) {
1422 return a - b;
5967 return Math.sqrt(variance);
6068 }
6169
62−module.exports = { add, multiply, subtract, divide, power, mean, median, standard_deviation };
70+module.exports = { add, multiply, subtract, divide, mod, power, mean, median, standard_deviation };
+5−0
66 assert.strictEqual(math.multiply(4, 5), 20);
77 assert.strictEqual(math.divide(10, 4), 2.5);
88 assert.throws(() => math.divide(1, 0), RangeError);
9+assert.strictEqual(math.mod(7, 3), 1);
10+assert.strictEqual(math.mod(-1, 3), 2);
11+assert.strictEqual(math.mod(6, 3), 0);
12+assert.strictEqual(math.mod(-1, -3), 2);
13+assert.throws(() => math.mod(1, 0), RangeError);
914 assert.strictEqual(math.power(2, 10), 1024);
1015 assert.strictEqual(math.power(5, 0), 1);
1116 assert.throws(() => math.power(2, -1), RangeError);