source: imaps-frontend/node_modules/nanoid/index.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 1.3 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 -= 0))
18 return pool.subarray(poolOffset - bytes, poolOffset)
19}
20let customRandom = (alphabet, defaultSize, getRandom) => {
21 let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
22 let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
23 return (size = defaultSize) => {
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 = 21) =>
36 customRandom(alphabet, size, random)
37let nanoid = (size = 21) => {
38 fillPool((size -= 0))
39 let id = ''
40 for (let i = poolOffset - size; i < poolOffset; i++) {
41 id += urlAlphabet[pool[i] & 63]
42 }
43 return id
44}
45export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
Note: See TracBrowser for help on using the repository browser.