CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
index.js63 linesDownload Raw Back to nanoid
1import crypto from 'crypto'2 3import { urlAlphabet } from './url-alphabet/index.js'4 5const POOL_SIZE_MULTIPLIER = 1286let pool, poolOffset7 8let fillPool = bytes => {9  if (bytes < 0) throw new RangeError('Wrong ID size')10  try {11    if (!pool || pool.length < bytes) {12      pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)13      crypto.randomFillSync(pool)14      poolOffset = 015    } else if (poolOffset + bytes > pool.length) {16      crypto.randomFillSync(pool)17      poolOffset = 018    }19  } catch (e) {20    pool = undefined21    throw e22  }23  poolOffset += bytes24}25 26let random = bytes => {27  fillPool((bytes |= 0))28  return pool.subarray(poolOffset - bytes, poolOffset)29}30 31let customRandom = (alphabet, defaultSize, getRandom) => {32  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 133 34 35  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)36 37  return (size = defaultSize) => {38    let id = ''39    while (true) {40      let bytes = getRandom(step)41      let i = step42      while (i--) {43        id += alphabet[bytes[i] & mask] || ''44        if (id.length === size) return id45      }46    }47  }48}49 50let customAlphabet = (alphabet, size = 21) =>51  customRandom(alphabet, size, random)52 53let nanoid = (size = 21) => {54  fillPool((size |= 0))55  let id = ''56  for (let i = poolOffset - size; i < poolOffset; i++) {57    id += urlAlphabet[pool[i] & 63]58  }59  return id60}61 62export { nanoid, customAlphabet, customRandom, urlAlphabet, random }63