-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
44 lines (40 loc) · 1.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void function(root){
function defaults(options){
var options = options || {}
var min = options.min
var max = options.max
var integer = options.integer || false
if ( min == null && max == null ) {
min = 0
max = 1
} else if ( min == null ) {
min = max - 1
} else if ( max == null ) {
max = min + 1
}
if ( max < min ) throw new Error('invalid options, max must be >= min')
return {
min: min
, max: max
, integer: integer
}
}
function random(options){
options = defaults(options)
if ( options.max === options.min ) return options.min
var r = Math.random() * (options.max - options.min + Number(!!options.integer)) + options.min
return options.integer ? Math.floor(r) : r
}
function generator(options){
options = defaults(options)
return function(min, max, integer){
options.min = min != null ? min : options.min
options.max = max != null ? max : options.max
options.integer = integer != null ? integer : options.integer
return random(options)
}
}
module.exports = random
module.exports.generator = generator
module.exports.defaults = defaults
}(this)