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