uuid.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // prep-work
  2. const _data = new Uint8Array(16);
  3. const _hex = [];
  4. for (let i = 0; i < 256; i++) {
  5. _hex.push(i.toString(16).padStart(2, '0'));
  6. }
  7. // todo@jrieken - with node@15 crypto#getRandomBytes is available everywhere, https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#browser_compatibility
  8. let _fillRandomValues;
  9. if (typeof crypto === 'object' && typeof crypto.getRandomValues === 'function') {
  10. // browser
  11. _fillRandomValues = crypto.getRandomValues.bind(crypto);
  12. }
  13. else {
  14. _fillRandomValues = function (bucket) {
  15. for (let i = 0; i < bucket.length; i++) {
  16. bucket[i] = Math.floor(Math.random() * 256);
  17. }
  18. return bucket;
  19. };
  20. }
  21. export function generateUuid() {
  22. // get data
  23. _fillRandomValues(_data);
  24. // set version bits
  25. _data[6] = (_data[6] & 0x0f) | 0x40;
  26. _data[8] = (_data[8] & 0x3f) | 0x80;
  27. // print as string
  28. let i = 0;
  29. let result = '';
  30. result += _hex[_data[i++]];
  31. result += _hex[_data[i++]];
  32. result += _hex[_data[i++]];
  33. result += _hex[_data[i++]];
  34. result += '-';
  35. result += _hex[_data[i++]];
  36. result += _hex[_data[i++]];
  37. result += '-';
  38. result += _hex[_data[i++]];
  39. result += _hex[_data[i++]];
  40. result += '-';
  41. result += _hex[_data[i++]];
  42. result += _hex[_data[i++]];
  43. result += '-';
  44. result += _hex[_data[i++]];
  45. result += _hex[_data[i++]];
  46. result += _hex[_data[i++]];
  47. result += _hex[_data[i++]];
  48. result += _hex[_data[i++]];
  49. result += _hex[_data[i++]];
  50. return result;
  51. }