random.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var baseRandom = require('../internal/baseRandom'),
  2. isIterateeCall = require('../internal/isIterateeCall');
  3. /* Native method references for those with the same name as other `lodash` methods. */
  4. var nativeMin = Math.min,
  5. nativeRandom = Math.random;
  6. /**
  7. * Produces a random number between `min` and `max` (inclusive). If only one
  8. * argument is provided a number between `0` and the given number is returned.
  9. * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
  10. * number is returned instead of an integer.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @category Number
  15. * @param {number} [min=0] The minimum possible value.
  16. * @param {number} [max=1] The maximum possible value.
  17. * @param {boolean} [floating] Specify returning a floating-point number.
  18. * @returns {number} Returns the random number.
  19. * @example
  20. *
  21. * _.random(0, 5);
  22. * // => an integer between 0 and 5
  23. *
  24. * _.random(5);
  25. * // => also an integer between 0 and 5
  26. *
  27. * _.random(5, true);
  28. * // => a floating-point number between 0 and 5
  29. *
  30. * _.random(1.2, 5.2);
  31. * // => a floating-point number between 1.2 and 5.2
  32. */
  33. function random(min, max, floating) {
  34. if (floating && isIterateeCall(min, max, floating)) {
  35. max = floating = undefined;
  36. }
  37. var noMin = min == null,
  38. noMax = max == null;
  39. if (floating == null) {
  40. if (noMax && typeof min == 'boolean') {
  41. floating = min;
  42. min = 1;
  43. }
  44. else if (typeof max == 'boolean') {
  45. floating = max;
  46. noMax = true;
  47. }
  48. }
  49. if (noMin && noMax) {
  50. max = 1;
  51. noMax = false;
  52. }
  53. min = +min || 0;
  54. if (noMax) {
  55. max = min;
  56. min = 0;
  57. } else {
  58. max = +max || 0;
  59. }
  60. if (floating || min % 1 || max % 1) {
  61. var rand = nativeRandom();
  62. return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
  63. }
  64. return baseRandom(min, max);
  65. }
  66. module.exports = random;