-
Notifications
You must be signed in to change notification settings - Fork 0
/
rng.js
63 lines (61 loc) · 1.7 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
59
60
61
62
63
/**
* String hashing
* @param {String} str
* @returns {Number[]}
*/
function cyrb128(str) {
var h1 = 1779033703, h2 = 3144134277,
h3 = 1013904242, h4 = 2773480762;
for (var i = 0, k; i < str.length; i++) {
k = str.charCodeAt(i);
h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
}
h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
h1 ^= (h2 ^ h3 ^ h4), h2 ^= h1, h3 ^= h1, h4 ^= h1;
return [h1>>>0, h2>>>0, h3>>>0, h4>>>0];
}
/**
* Simple Fast Counter RNG
* @param {String|Number} seed
* @param {Number} seedn
* @returns {()=>Number} RNG function that return 0..1
*/
function sfc32(seed, ...seedn) {
var a, b, c, d;
if(seed instanceof Number) {
a = 0x9E3779B9;
b = 0x243F6A88;
c = 0xB7E15162;
d = seed;
} else {
seed = cyrb128(seed);
a = seed[0];
b = seed[1];
c = seed[2];
d = seed[3];
}
return function() {
a |= 0; b |= 0; c |= 0; d |= 0;
var t = (a + b | 0) + d | 0;
d = d + 1 | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
c = c + t | 0;
return (t >>> 0) / 4294967296;
}
}
function randomSeed(len=8) {
const ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var result = "";
for(var i = 0; i < len; i++) {
result += ch[Math.floor(Math.random() * ch.length)];
}
return result;
}