25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.3 KiB

4 년 전
  1. var baseRandom = require('./_baseRandom'),
  2. isIterateeCall = require('./_isIterateeCall'),
  3. toFinite = require('./toFinite');
  4. /** Built-in method references without a dependency on `root`. */
  5. var freeParseFloat = parseFloat;
  6. /* Built-in method references for those with the same name as other `lodash` methods. */
  7. var nativeMin = Math.min,
  8. nativeRandom = Math.random;
  9. /**
  10. * Produces a random number between the inclusive `lower` and `upper` bounds.
  11. * If only one argument is provided a number between `0` and the given number
  12. * is returned. If `floating` is `true`, or either `lower` or `upper` are
  13. * floats, a floating-point number is returned instead of an integer.
  14. *
  15. * **Note:** JavaScript follows the IEEE-754 standard for resolving
  16. * floating-point values which can produce unexpected results.
  17. *
  18. * @static
  19. * @memberOf _
  20. * @since 0.7.0
  21. * @category Number
  22. * @param {number} [lower=0] The lower bound.
  23. * @param {number} [upper=1] The upper bound.
  24. * @param {boolean} [floating] Specify returning a floating-point number.
  25. * @returns {number} Returns the random number.
  26. * @example
  27. *
  28. * _.random(0, 5);
  29. * // => an integer between 0 and 5
  30. *
  31. * _.random(5);
  32. * // => also an integer between 0 and 5
  33. *
  34. * _.random(5, true);
  35. * // => a floating-point number between 0 and 5
  36. *
  37. * _.random(1.2, 5.2);
  38. * // => a floating-point number between 1.2 and 5.2
  39. */
  40. function random(lower, upper, floating) {
  41. if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
  42. upper = floating = undefined;
  43. }
  44. if (floating === undefined) {
  45. if (typeof upper == 'boolean') {
  46. floating = upper;
  47. upper = undefined;
  48. }
  49. else if (typeof lower == 'boolean') {
  50. floating = lower;
  51. lower = undefined;
  52. }
  53. }
  54. if (lower === undefined && upper === undefined) {
  55. lower = 0;
  56. upper = 1;
  57. }
  58. else {
  59. lower = toFinite(lower);
  60. if (upper === undefined) {
  61. upper = lower;
  62. lower = 0;
  63. } else {
  64. upper = toFinite(upper);
  65. }
  66. }
  67. if (lower > upper) {
  68. var temp = lower;
  69. lower = upper;
  70. upper = temp;
  71. }
  72. if (floating || lower % 1 || upper % 1) {
  73. var rand = nativeRandom();
  74. return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
  75. }
  76. return baseRandom(lower, upper);
  77. }
  78. module.exports = random;