Last change
on this file since eed0bf8 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
981 bytes
|
Line | |
---|
1 | let random = bytes =>
|
---|
2 | Promise.resolve(crypto.getRandomValues(new Uint8Array(bytes)))
|
---|
3 | let customAlphabet = (alphabet, size) => {
|
---|
4 | let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
|
---|
5 | let step = -~((1.6 * mask * size) / alphabet.length)
|
---|
6 | return () => {
|
---|
7 | let id = ''
|
---|
8 | while (true) {
|
---|
9 | let bytes = crypto.getRandomValues(new Uint8Array(step))
|
---|
10 | let i = step
|
---|
11 | while (i--) {
|
---|
12 | id += alphabet[bytes[i] & mask] || ''
|
---|
13 | if (id.length === size) return Promise.resolve(id)
|
---|
14 | }
|
---|
15 | }
|
---|
16 | }
|
---|
17 | }
|
---|
18 | let nanoid = (size = 21) => {
|
---|
19 | let id = ''
|
---|
20 | let bytes = crypto.getRandomValues(new Uint8Array(size))
|
---|
21 | while (size--) {
|
---|
22 | let byte = bytes[size] & 63
|
---|
23 | if (byte < 36) {
|
---|
24 | id += byte.toString(36)
|
---|
25 | } else if (byte < 62) {
|
---|
26 | id += (byte - 26).toString(36).toUpperCase()
|
---|
27 | } else if (byte < 63) {
|
---|
28 | id += '_'
|
---|
29 | } else {
|
---|
30 | id += '-'
|
---|
31 | }
|
---|
32 | }
|
---|
33 | return Promise.resolve(id)
|
---|
34 | }
|
---|
35 | module.exports = { nanoid, customAlphabet, random }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.