source: trip-planner-front/node_modules/nanoid/async/index.js@ e29cc2e

Last change on this file since e29cc2e was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 921 bytes
Line 
1import crypto from 'crypto'
2import { urlAlphabet } from '../url-alphabet/index.js'
3let 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 })
13let 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}
27let 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 })
35export { nanoid, customAlphabet, random }
Note: See TracBrowser for help on using the repository browser.