-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathid.mjs
More file actions
39 lines (34 loc) · 1.01 KB
/
id.mjs
File metadata and controls
39 lines (34 loc) · 1.01 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
const DIGITS = '0123456789';
const LOWER = 'abcdefghijklmnopqrstuvwxyz';
const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const CHARS = DIGITS + LOWER + UPPER + '-_';
const CHARS_LENGTH = CHARS.length;
const POSSIBLE = new Uint8Array(CHARS_LENGTH);
for (let i = 0; i < CHARS_LENGTH; i++) {
POSSIBLE[i] = CHARS[i].charCodeAt(0);
}
const DEFAULT_LENGTH = 24;
const BUF_SIZE = DEFAULT_LENGTH * 1024;
const randomPrefetcher = {
buf: crypto.getRandomValues(new Uint8Array(BUF_SIZE)),
pos: 0,
next(length = DEFAULT_LENGTH) {
const { buf, pos } = this;
let start = pos;
if (start + length > buf.length) {
start = 0;
crypto.getRandomValues(buf);
}
const end = start + length;
this.pos = end;
return buf.subarray(start, end);
},
};
const generateID = (n = DEFAULT_LENGTH) => {
const randomBytes = randomPrefetcher.next(n);
for (let i = 0; i < n; i++) {
randomBytes[i] = POSSIBLE[randomBytes[i] & 0x3f];
}
return String.fromCharCode(...randomBytes);
};
export { generateID, CHARS };