toSafeInteger.js 836 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. var baseClamp = require('./_baseClamp'),
  2. toInteger = require('./toInteger');
  3. /** Used as references for various `Number` constants. */
  4. var MAX_SAFE_INTEGER = 9007199254740991;
  5. /**
  6. * Converts `value` to a safe integer. A safe integer can be compared and
  7. * represented correctly.
  8. *
  9. * @static
  10. * @memberOf _
  11. * @since 4.0.0
  12. * @category Lang
  13. * @param {*} value The value to convert.
  14. * @returns {number} Returns the converted integer.
  15. * @example
  16. *
  17. * _.toSafeInteger(3.2);
  18. * // => 3
  19. *
  20. * _.toSafeInteger(Number.MIN_VALUE);
  21. * // => 0
  22. *
  23. * _.toSafeInteger(Infinity);
  24. * // => 9007199254740991
  25. *
  26. * _.toSafeInteger('3.2');
  27. * // => 3
  28. */
  29. function toSafeInteger(value) {
  30. return value
  31. ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
  32. : (value === 0 ? value : 0);
  33. }
  34. module.exports = toSafeInteger;