1
0
mirror of https://github.com/MikeMcl/decimal.js.git synced 2026-09-23 04:14:32 +00:00

#101 Add clamp method

This commit is contained in:
Michael Mclaughlin
2021-06-22 12:15:13 +01:00
parent ac0711318f
commit d102ead7af
6 changed files with 157 additions and 24 deletions

View File

@@ -127,6 +127,7 @@ var EXP_LIMIT = 9e15, // 0 to 9e15
/*
* absoluteValue abs
* ceil
* clampedTo clamp
* comparedTo cmp
* cosine cos
* cubeRoot cbrt
@@ -208,6 +209,26 @@ P.ceil = function () {
};
/*
* Return a new Decimal whose value is the value of this Decimal clamped to the range
* delineated by `min` and `max`.
*
* min {number|string|Decimal}
* max {number|string|Decimal}
*
*/
P.clampedTo = P.clamp = function (min, max) {
var k,
x = this,
Ctor = x.constructor;
min = new Ctor(min);
max = new Ctor(max);
if (!min.s || !max.s || min.gt(max)) return new Ctor(NaN);
k = x.cmp(min);
return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);
};
/*
* Return
* 1 if the value of this Decimal is greater than the value of `y`,
@@ -2441,18 +2462,6 @@ P.valueOf = P.toJSON = function () {
};
/*
// Add aliases to match BigDecimal method names.
// P.add = P.plus;
P.subtract = P.minus;
P.multiply = P.times;
P.divide = P.div;
P.remainder = P.mod;
P.compareTo = P.cmp;
P.negate = P.neg;
*/
// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
@@ -3930,6 +3939,7 @@ function truncate(arr, len) {
* atan2
* cbrt
* ceil
* clamp
* clone
* config
* cos
@@ -4149,6 +4159,19 @@ function ceil(x) {
}
/*
* Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`.
*
* x {number|string|Decimal}
* min {number|string|Decimal}
* max {number|string|Decimal}
*
*/
function clamp(x, min, max) {
return new this(x).clamp(min, max);
}
/*
* Configure global settings for a Decimal constructor.
*
@@ -4382,6 +4405,7 @@ function clone(obj) {
Decimal.atan2 = atan2;
Decimal.cbrt = cbrt; // ES6
Decimal.ceil = ceil;
Decimal.clamp = clamp;
Decimal.cos = cos;
Decimal.cosh = cosh; // ES6
Decimal.div = div;