-
Notifications
You must be signed in to change notification settings - Fork 4
/
rng.js
58 lines (50 loc) · 1.09 KB
/
rng.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import seedrandom from 'seedrandom';
/**
* Stateful PRNG example
*
* seed(str) {
* // initial seed will give you a number and a state
* const seed = rng({ seed: str });
* // save this state
* this.setState({ rng: seed.state });
* }
*
* rng() {
* const result = rng(this.state.rng);
* this.setState({ rng: result.state });
* return rng.number;
* }
*
*/
function _rng(state = {}, handler = gen => gen()) {
const seed = state.seed;
const options = {
state: state.arc || {},
};
const result = seedrandom(seed, options);
return {
number: handler(result),
state: {
seed,
arc: result.state(),
count: (state.count || 0) + 1,
},
};
}
export default function rng(state) {
return _rng(state);
}
export function custom(state, handler) {
return _rng(state, handler);
}
export function int(state) {
return _rng(state, gen => gen.int32());
}
// split one random number
export function splitChance({split, chance}) {
const match = chance < split;
return {
match,
chance: match ? chance / split : (chance - split) / (1 - split),
};
}