clamp.js 890 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var baseClamp = require('./_baseClamp'),
  2. toNumber = require('./toNumber');
  3. /**
  4. * Clamps `number` within the inclusive `lower` and `upper` bounds.
  5. *
  6. * @static
  7. * @memberOf _
  8. * @since 4.0.0
  9. * @category Number
  10. * @param {number} number The number to clamp.
  11. * @param {number} [lower] The lower bound.
  12. * @param {number} upper The upper bound.
  13. * @returns {number} Returns the clamped number.
  14. * @example
  15. *
  16. * _.clamp(-10, -5, 5);
  17. * // => -5
  18. *
  19. * _.clamp(10, -5, 5);
  20. * // => 5
  21. */
  22. function clamp(number, lower, upper) {
  23. if (upper === undefined) {
  24. upper = lower;
  25. lower = undefined;
  26. }
  27. if (upper !== undefined) {
  28. upper = toNumber(upper);
  29. upper = upper === upper ? upper : 0;
  30. }
  31. if (lower !== undefined) {
  32. lower = toNumber(lower);
  33. lower = lower === lower ? lower : 0;
  34. }
  35. return baseClamp(toNumber(number), lower, upper);
  36. }
  37. module.exports = clamp;