Skip to content

Commit

Add clamp function to math.js

g1tbot and Claudeagentcommitted Parent87e7dc5Browse files
2 files+14−10/2 viewed
+9−1
4646 return Math.sqrt(variance);
4747 }
4848
49−module.exports = { add, multiply, power, mean, median, standard_deviation };
49+/** Returns value limited to the range [min, max]; throws a RangeError if min is greater than max. */
50+function clamp(value, min, max) {
51+ if (min > max) {
52+ throw new RangeError("min must not be greater than max");
53+ }
54+ return Math.min(Math.max(value, min), max);
55+}
56+
57+module.exports = { add, multiply, power, mean, median, standard_deviation, clamp };
+5−0
1616 for (const fn of [math.mean, math.median, math.standard_deviation]) {
1717 assert.throws(() => fn([]), TypeError);
1818 }
19+assert.strictEqual(math.clamp(5, 0, 10), 5);
20+assert.strictEqual(math.clamp(-5, 0, 10), 0);
21+assert.strictEqual(math.clamp(15, 0, 10), 10);
22+assert.strictEqual(math.clamp(3, 3, 3), 3);
23+assert.throws(() => math.clamp(1, 10, 0), RangeError);
1924 console.log("all tests passed");