CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
index.cjs58 linesDownload Raw Back to nanoid
1let crypto = require('crypto')2 3let { urlAlphabet } = require('./url-alphabet/index.cjs')4 5const POOL_SIZE_MULTIPLIER = 1286let pool, poolOffset7 8let fillPool = bytes => {9  if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size')10  if (!pool || pool.length < bytes) {11    pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)12    crypto.randomFillSync(pool)13    poolOffset = 014  } else if (poolOffset + bytes > pool.length) {15    crypto.randomFillSync(pool)16    poolOffset = 017  }18  poolOffset += bytes19}20 21let random = bytes => {22  fillPool((bytes |= 0))23  return pool.subarray(poolOffset - bytes, poolOffset)24}25 26let customRandom = (alphabet, defaultSize, getRandom) => {27  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 128 29 30  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)31 32  return (size = defaultSize) => {33    let id = ''34    while (true) {35      let bytes = getRandom(step)36      let i = step37      while (i--) {38        id += alphabet[bytes[i] & mask] || ''39        if (id.length === size) return id40      }41    }42  }43}44 45let customAlphabet = (alphabet, size = 21) =>46  customRandom(alphabet, size, random)47 48let nanoid = (size = 21) => {49  fillPool((size |= 0))50  let id = ''51  for (let i = poolOffset - size; i < poolOffset; i++) {52    id += urlAlphabet[pool[i] & 63]53  }54  return id55}56 57module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }58