stringify.js 1.6 KB

12345678910111213141516171819202122232425262728293031
  1. import validate from './validate.js';
  2. /**
  3. * Convert array of 16 byte values to UUID string format of the form:
  4. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  5. */
  6. const byteToHex = [];
  7. for (let i = 0; i < 256; ++i) {
  8. byteToHex.push((i + 0x100).toString(16).slice(1));
  9. }
  10. export function unsafeStringify(arr, offset = 0) {
  11. // Note: Be careful editing this code! It's been tuned for performance
  12. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  13. //
  14. // Note to future-self: No, you can't remove the `toLowerCase()` call.
  15. // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351
  16. return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
  17. }
  18. function stringify(arr, offset = 0) {
  19. const uuid = unsafeStringify(arr, offset);
  20. // Consistency check for valid UUID. If this throws, it's likely due to one
  21. // of the following:
  22. // - One or more input array values don't map to a hex octet (leading to
  23. // "undefined" in the uuid)
  24. // - Invalid input values for the RFC `version` or `variant` fields
  25. if (!validate(uuid)) {
  26. throw TypeError('Stringified UUID is invalid');
  27. }
  28. return uuid;
  29. }
  30. export default stringify;