clamp.js 546 B

12345678910111213141516
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = require('es-errors/type');
  4. var max = GetIntrinsic('%Math.max%');
  5. var min = GetIntrinsic('%Math.min%');
  6. // https://262.ecma-international.org/12.0/#clamping
  7. module.exports = function clamp(x, lower, upper) {
  8. if (typeof x !== 'number' || typeof lower !== 'number' || typeof upper !== 'number' || !(lower <= upper)) {
  9. throw new $TypeError('Assertion failed: all three arguments must be MVs, and `lower` must be `<= upper`');
  10. }
  11. return min(max(lower, x), upper);
  12. };