random-id.js 682 B

12345678910111213141516171819202122
  1. const CHARSET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  2. export function createRandomId(length = 32, prefixWithU = true, radix = null) {
  3. const base = radix || CHARSET.length
  4. const chars = []
  5. if (length) {
  6. for (let i = 0; i < length; i++) {
  7. chars.push(CHARSET[Math.floor(Math.random() * base)])
  8. }
  9. } else {
  10. chars[8] = chars[13] = chars[18] = chars[23] = '-'
  11. chars[14] = '4'
  12. for (let i = 0; i < 36; i++) {
  13. if (!chars[i]) {
  14. const r = Math.floor(Math.random() * 16)
  15. chars[i] = CHARSET[i === 19 ? (r & 0x3) | 0x8 : r]
  16. }
  17. }
  18. }
  19. const joined = prefixWithU && length ? 'u' + chars.join('') : chars.join('')
  20. return joined
  21. }