UNPKG

clamp-it

Version:
90 lines (89 loc) 2.83 kB
"use strict"; ///////////////////////////////// Public API ///////////////////////////////// Object.defineProperty(exports, "__esModule", { value: true }); exports.within = exports.atMost = exports.atLeast = void 0; /** * Clamp values that must be greater than or equal to the given minimum. */ function atLeast(minimum) { return new AtLeast(minimum); } exports.atLeast = atLeast; /** * Clamp values that must be less than or equal to the given minimum. */ function atMost(maximum) { return new AtMost(maximum); } exports.atMost = atMost; /** * Clamp values that must be bound within a given closed range. * The order of the arguments does not matter. */ function within(a, b) { if (b < a) return new Within(b, a); return new Within(a, b); } exports.within = within; var AtLeast = /** @class */ (function () { function AtLeast(minimum) { if (isNaN(minimum)) { throw new RangeError("bound must be a number, but got NaN"); } this._min = minimum; } AtLeast.prototype.clamp = function (value) { return Math.max(this._min, value); }; AtLeast.prototype.atLeast = function (minimum) { return new AtLeast(this.clamp(minimum)); }; AtLeast.prototype.atMost = function (maximum) { return new Within(this._min, maximum); }; return AtLeast; }()); var AtMost = /** @class */ (function () { function AtMost(maximum) { if (isNaN(maximum)) { throw new RangeError("bound must be a number, but got NaN"); } this._max = maximum; } AtMost.prototype.clamp = function (value) { return Math.min(this._max, value); }; AtMost.prototype.atLeast = function (minimum) { return new Within(minimum, this._max); }; AtMost.prototype.atMost = function (maximum) { return new AtMost(this.clamp(maximum)); }; return AtMost; }()); var Within = /** @class */ (function () { function Within(minimum, maximum) { if (isNaN(minimum)) { throw new RangeError("minimum must be a number, but got NaN"); } if (isNaN(maximum)) { throw new RangeError("maximum must be a number, but got NaN"); } if (minimum > maximum) { throw new RangeError("contradictory bounds: " + minimum + " was not less than or equal to " + maximum); } this._min = minimum; this._max = maximum; } Within.prototype.clamp = function (value) { return Math.min(this._max, Math.max(this._min, value)); }; Within.prototype.atLeast = function (minimum) { return new Within(this.clamp(minimum), this._max); }; Within.prototype.atMost = function (maximum) { return new Within(this._min, this.clamp(maximum)); }; return Within; }());