number.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. // http://www.2ality.com/2013/10/safe-integers.html
  3. // http://es6.ruanyifeng.com/#docs/number
  4. exports.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
  5. exports.MIN_SAFE_INTEGER = -exports.MAX_SAFE_INTEGER;
  6. var MAX_SAFE_INTEGER_STR = exports.MAX_SAFE_INTEGER_STR = String(exports.MAX_SAFE_INTEGER);
  7. var MAX_SAFE_INTEGER_STR_LENGTH = MAX_SAFE_INTEGER_STR.length;
  8. /**
  9. * Detect a number string can safe convert to Javascript Number.
  10. *
  11. * @param {String} s number format string, like `"123"`, `"-1000123123123123123123"`
  12. * @return {Boolean}
  13. */
  14. exports.isSafeNumberString = function isSafeNumberString(s) {
  15. if (s[0] === '-') {
  16. s = s.substring(1);
  17. }
  18. if (s.length < MAX_SAFE_INTEGER_STR_LENGTH ||
  19. (s.length === MAX_SAFE_INTEGER_STR_LENGTH && s <= MAX_SAFE_INTEGER_STR)) {
  20. return true;
  21. }
  22. return false;
  23. };
  24. /**
  25. * Convert string to Number if string in safe Number scope.
  26. *
  27. * @param {String} s number format string.
  28. * @return {Number|String} success will return Number, otherise return the original string.
  29. */
  30. exports.toSafeNumber = function toSafeNumber(s) {
  31. if (typeof s === 'number') {
  32. return s;
  33. }
  34. return exports.isSafeNumberString(s) ? Number(s) : s;
  35. };
  36. /**
  37. * Produces a random integer between the inclusive `lower` and `upper` bounds.
  38. *
  39. * @param {Number} lower The lower bound.
  40. * @param {Number} upper The upper bound.
  41. * @return {Number} Returns the random number.
  42. */
  43. exports.random = function random(lower, upper) {
  44. if (lower === undefined && upper === undefined) {
  45. return 0;
  46. }
  47. if (upper === undefined) {
  48. upper = lower;
  49. lower = 0;
  50. }
  51. var temp;
  52. if (lower > upper) {
  53. temp = lower;
  54. lower = upper;
  55. upper = temp;
  56. }
  57. return Math.floor(lower + Math.random() * (upper - lower));
  58. };