index.browser.cjs 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  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. crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
  22. byte &= 63
  23. if (byte < 36) {
  24. id += byte.toString(36)
  25. } else if (byte < 62) {
  26. id += (byte - 26).toString(36).toUpperCase()
  27. } else if (byte > 62) {
  28. id += '-'
  29. } else {
  30. id += '_'
  31. }
  32. return id
  33. }, '')
  34. module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }