clamp.js 576 B

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