-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
188 lines (169 loc) · 4.76 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
* @param {string} msg
*/
const tag = msg => `[@manutero/randomjs] ${msg}`
/**
* "Mulberry32 is a simple generator with a 32-bit state, but is extremely fast and has good quality"
* @see https://stackoverflow.com/a/47593316/1614677
* @param {number} seed
* @return {() => number} (0,1)
*/
const mulberry32 = seed => {
return () => {
let t = (seed += 0x6d2b79f5)
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/**
* @param {number=} seed
*/
const RandomGenerator = seed => {
const actualSeed = seed || Math.random() * 100000000000
const unit = mulberry32(actualSeed)
/**
* @param {number} a natural number, inclusive.
* @param {number} b natural number, inclusive.
* @param {object} param2
* @param {boolean} param2.round
*/
const n = (a, b, { round }) => {
if (a > b) {
throw new TypeError(tag('a is greater than b'))
}
const response = unit() * (b - a + 1) + a
return round ? Math.floor(response) : response
}
/**
* @param {number} a natural number, inclusive.
* @param {number} b natural number, inclusive.
*/
const number = (a, b) => n(a, b, { round: true })
/**
* @param {number} a inclusive.
* @param {number} b inclusive.
*/
const real = (a, b) => n(a, b, { round: false })
/**
* @param {string} success "30%"
*/
const play = success => {
console.warn(tag('DEPRECATED'))
console.warn(tag('to be removed on v1.0.0'))
return number(1, 100) <= parseInt(success.split('%')[0])
}
/**
* @param {number} success chance of success as float; e.g. 42.0
*/
const bet = success => real(0, 100) <= success
/**
* @param {string} dices 'd6' '1D6' '3d12' '2d20' ("d<num>" or "<num>d<num>")
*/
const roll = dices => {
if (typeof dices !== 'string') {
throw new TypeError(tag('dices is not an string'))
}
let diceNumber
let sides
try {
const input = dices.toLowerCase().split('d')
diceNumber = parseInt(input[0]) || 1
sides = parseInt(input[1])
} catch (err) {
throw new TypeError(tag('dices is not formatted /<num>d<num>/'))
}
if (isNaN(diceNumber) || isNaN(sides)) {
throw new TypeError(tag('dices is not formatted /<num>d<num>/'))
}
const results = []
for (let i = 0; i < diceNumber; i++) {
results.push(number(1, sides))
}
return results
}
/**
* @param {Array<number>} weights
*/
const chooseWeightedIndex = weights => {
let acc = 0
// if the weights are [5, 30, 10],
// this would build an array containing [5, 35, 45], and acc=45
const ranges = weights.map(weight => (acc += weight))
const selectedValue = unit() * acc
// If the selected value is within one of the ranges, that's our choice!
for (let index = 0; index < ranges.length; index++) {
if (selectedValue < ranges[index]) {
return index
}
}
// If nothing was chosen, all weights were 0 or something went wrong.
return -1
}
/**
* @param {Array<any>} arr
* @param {object} param1
* @param {string=} param1.weightKey
* @param {string=} param1.valueKey
* @example
* ```js
* rn.pickOne(['a', 'b', 'c'])
* ```
*
* ```js
* rn.pickOne([
* { key: "Human", weight: 999 },
* { key: "Extraterrestrial", weight: 1 },
* ])
* ```
*/
const pickOne = (arr, { weightKey } = { weightKey: 'weight' }) => {
if (!arr || arr.length <= 0) {
return null
}
if (typeof arr[0] !== 'object') {
return arr[number(0, arr.length - 1)]
}
const weights = arr
.filter(item => (item[weightKey] !== undefined ? item[weightKey] : 1) > 0)
.map(item => item[weightKey] || 1)
const selectedIndex = chooseWeightedIndex(weights)
return selectedIndex >= 0 ? arr[selectedIndex] : null
}
/**
*
* @param {number} min
* @param {number} max
* @param {object} param0
* @param {number=} param0.skew
* @param {boolean=} param0.round
*
* @see https://stackoverflow.com/a/49434653/1614677
*/
const normal = (min, max, { skew, round } = { skew: 1, round: true }) => {
const u = unit() // (0,1)
const v = unit() // (0,1)
let num = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v)
num = num / 10.0 + 0.5 // Translate to 0 -> 1
if (num > 1 || num < 0) {
// resample between 0 and 1 if out of range
num = normal(min, max, { skew })
}
num = Math.pow(num, skew) // Skew
num *= max - min // Stretch to fill range
num += min // offset to min
return round ? Math.round(num) : num
}
return {
normal,
number,
pickOne,
roll,
play, /* to be removed */
bet,
real,
unit,
seed: actualSeed
}
}
module.exports = { RandomGenerator }