index.browser.cjs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. let { urlAlphabet } = require('./url-alphabet/index.cjs')
  2. let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
  3. let customRandom = (alphabet, defaultSize, getRandom) => {
  4. let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
  5. let step = -~((1.6 * mask * defaultSize) / alphabet.length)
  6. return (size = defaultSize) => {
  7. let id = ''
  8. while (true) {
  9. let bytes = getRandom(step)
  10. let j = step
  11. while (j--) {
  12. id += alphabet[bytes[j] & mask] || ''
  13. if (id.length === size) return id
  14. }
  15. }
  16. }
  17. }
  18. let customAlphabet = (alphabet, size = 21) =>
  19. customRandom(alphabet, size, random)
  20. let nanoid = (size = 21) => {
  21. let id = ''
  22. let bytes = crypto.getRandomValues(new Uint8Array(size))
  23. while (size--) {
  24. let byte = bytes[size] & 63
  25. if (byte < 36) {
  26. id += byte.toString(36)
  27. } else if (byte < 62) {
  28. id += (byte - 26).toString(36).toUpperCase()
  29. } else if (byte < 63) {
  30. id += '_'
  31. } else {
  32. id += '-'
  33. }
  34. }
  35. return id
  36. }
  37. module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }