uuid.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. export const generateUuid = (function () {
  2. // use `randomUUID` if possible
  3. if (typeof crypto === 'object' && typeof crypto.randomUUID === 'function') {
  4. return crypto.randomUUID.bind(crypto);
  5. }
  6. // use `randomValues` if possible
  7. let getRandomValues;
  8. if (typeof crypto === 'object' && typeof crypto.getRandomValues === 'function') {
  9. getRandomValues = crypto.getRandomValues.bind(crypto);
  10. }
  11. else {
  12. getRandomValues = function (bucket) {
  13. for (let i = 0; i < bucket.length; i++) {
  14. bucket[i] = Math.floor(Math.random() * 256);
  15. }
  16. return bucket;
  17. };
  18. }
  19. // prep-work
  20. const _data = new Uint8Array(16);
  21. const _hex = [];
  22. for (let i = 0; i < 256; i++) {
  23. _hex.push(i.toString(16).padStart(2, '0'));
  24. }
  25. return function generateUuid() {
  26. // get data
  27. getRandomValues(_data);
  28. // set version bits
  29. _data[6] = (_data[6] & 0x0f) | 0x40;
  30. _data[8] = (_data[8] & 0x3f) | 0x80;
  31. // print as string
  32. let i = 0;
  33. let result = '';
  34. result += _hex[_data[i++]];
  35. result += _hex[_data[i++]];
  36. result += _hex[_data[i++]];
  37. result += _hex[_data[i++]];
  38. result += '-';
  39. result += _hex[_data[i++]];
  40. result += _hex[_data[i++]];
  41. result += '-';
  42. result += _hex[_data[i++]];
  43. result += _hex[_data[i++]];
  44. result += '-';
  45. result += _hex[_data[i++]];
  46. result += _hex[_data[i++]];
  47. result += '-';
  48. result += _hex[_data[i++]];
  49. result += _hex[_data[i++]];
  50. result += _hex[_data[i++]];
  51. result += _hex[_data[i++]];
  52. result += _hex[_data[i++]];
  53. result += _hex[_data[i++]];
  54. return result;
  55. };
  56. })();