source: trip-planner-front/node_modules/nanoid/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: 1.2 KB
Line 
1import crypto from 'crypto'
2import { urlAlphabet } from './url-alphabet/index.js'
3const POOL_SIZE_MULTIPLIER = 128
4let pool, poolOffset
5let fillPool = bytes => {
6 if (!pool || pool.length < bytes) {
7 pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
8 crypto.randomFillSync(pool)
9 poolOffset = 0
10 } else if (poolOffset + bytes > pool.length) {
11 crypto.randomFillSync(pool)
12 poolOffset = 0
13 }
14 poolOffset += bytes
15}
16let random = bytes => {
17 fillPool(bytes)
18 return pool.subarray(poolOffset - bytes, poolOffset)
19}
20let customRandom = (alphabet, size, getRandom) => {
21 let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
22 let step = Math.ceil((1.6 * mask * size) / alphabet.length)
23 return () => {
24 let id = ''
25 while (true) {
26 let bytes = getRandom(step)
27 let i = step
28 while (i--) {
29 id += alphabet[bytes[i] & mask] || ''
30 if (id.length === size) return id
31 }
32 }
33 }
34}
35let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
36let nanoid = (size = 21) => {
37 fillPool(size)
38 let id = ''
39 for (let i = poolOffset - size; i < poolOffset; i++) {
40 id += urlAlphabet[pool[i] & 63]
41 }
42 return id
43}
44export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
Note: See TracBrowser for help on using the repository browser.