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:
921 bytes
|
Line | |
---|
1 | import crypto from 'crypto'
|
---|
2 | import { urlAlphabet } from '../url-alphabet/index.js'
|
---|
3 | let random = bytes =>
|
---|
4 | new Promise((resolve, reject) => {
|
---|
5 | crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
|
---|
6 | if (err) {
|
---|
7 | reject(err)
|
---|
8 | } else {
|
---|
9 | resolve(buf)
|
---|
10 | }
|
---|
11 | })
|
---|
12 | })
|
---|
13 | let customAlphabet = (alphabet, size) => {
|
---|
14 | let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
---|
15 | let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
---|
16 | let tick = id =>
|
---|
17 | random(step).then(bytes => {
|
---|
18 | let i = step
|
---|
19 | while (i--) {
|
---|
20 | id += alphabet[bytes[i] & mask] || ''
|
---|
21 | if (id.length === size) return id
|
---|
22 | }
|
---|
23 | return tick(id)
|
---|
24 | })
|
---|
25 | return () => tick('')
|
---|
26 | }
|
---|
27 | let nanoid = (size = 21) =>
|
---|
28 | random(size).then(bytes => {
|
---|
29 | let id = ''
|
---|
30 | while (size--) {
|
---|
31 | id += urlAlphabet[bytes[size] & 63]
|
---|
32 | }
|
---|
33 | return id
|
---|
34 | })
|
---|
35 | export { nanoid, customAlphabet, random }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.