toFinite.js 868 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var toNumber = require('./toNumber');
  2. /** Used as references for various `Number` constants. */
  3. var INFINITY = 1 / 0,
  4. MAX_INTEGER = 1.7976931348623157e+308;
  5. /**
  6. * Converts `value` to a finite number.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 4.12.0
  11. * @category Lang
  12. * @param {*} value The value to convert.
  13. * @returns {number} Returns the converted number.
  14. * @example
  15. *
  16. * _.toFinite(3.2);
  17. * // => 3.2
  18. *
  19. * _.toFinite(Number.MIN_VALUE);
  20. * // => 5e-324
  21. *
  22. * _.toFinite(Infinity);
  23. * // => 1.7976931348623157e+308
  24. *
  25. * _.toFinite('3.2');
  26. * // => 3.2
  27. */
  28. function toFinite(value) {
  29. if (!value) {
  30. return value === 0 ? value : 0;
  31. }
  32. value = toNumber(value);
  33. if (value === INFINITY || value === -INFINITY) {
  34. var sign = (value < 0 ? -1 : 1);
  35. return sign * MAX_INTEGER;
  36. }
  37. return value === value ? value : 0;
  38. }
  39. module.exports = toFinite;