Add clamp function to math.js
2 files+14−10/2 viewed
| 46 | 46 | return Math.sqrt(variance); | |
| 47 | 47 | } | |
| 48 | 48 | ||
| 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 }; |
| 16 | 16 | for (const fn of [math.mean, math.median, math.standard_deviation]) { | |
| 17 | 17 | assert.throws(() => fn([]), TypeError); | |
| 18 | 18 | } | |
| 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); | |
| 19 | 24 | console.log("all tests passed"); |