-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (56 loc) · 1.21 KB
/
Copy pathindex.js
File metadata and controls
65 lines (56 loc) · 1.21 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* `Chance` Constructor
* @param {Array} opts [containing weighted funcs]
*
* Example: [{
* w: 60,
* f: function (v) {
* console.log('Weight 60');
* }
* }]
*/
var Chance = function(opts) {
this._stack = opts;
this._found = new Array();
this._stack.sort(function (a, b) {
return a.w - b.w;
}).reduce(function (a, b) {
b.cw = b.w + a;
return a + b.w;
}, 0);
};
/**
* `Generate` Random number
*
* @api private
*/
Chance.prototype.random = function() {
var random = ~~ (Math.random() * 100);
while (this._found.indexOf(random) === -1) {
random = ~~ (Math.random() * 100);
this._found.push(random);
};
if (this._found.length === 100) {
this._found.length = 0;
};
return random;
}
/**
* `Get` next function, according to weight
*
* @return {Function} [executed]
*/
Chance.prototype.next = function() {
var random = this.random();
for (var i = 0; i < this._stack.length; i++) {
if (random <= this._stack[i].cw) {
this._stack[i].f.apply(this, arguments);
break;
}
};
};
/**
* `Expose` Chance
* @type {CommonJs}
*/
module.exports = Chance;