uuid.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. export default function getUuid(prefix: string) {
  2. return `${prefix}-${new Date().getTime()}-${Math.random()}`;
  3. }
  4. // https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
  5. function getUuidv4() {
  6. try {
  7. // @ts-ignore
  8. return crypto?.randomUUID?.() ?? (String(1e7 + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  9. (Number(c) ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16)
  10. ));
  11. } catch (err) {
  12. return getUuid('semi');
  13. }
  14. }
  15. /**
  16. * Get a random id with prefix, it not strictly guarantee id uniqueness
  17. *
  18. * Note: the return value of getUuid is too long, we need a short one
  19. *
  20. * @example
  21. * getUuidShort({ prefix: 'semi' }) => 'semi-46dinzc'
  22. * getUuidShort({ prefix: '' }) => '0eer2i0'
  23. * getUuidShort({ prefix: 'semi', length: 4 }) => 'semi-8jts'
  24. */
  25. function getUuidShort(options: GetUuidShortOptions = {}) {
  26. const { prefix = '', length = 7 } = options;
  27. const characters = '0123456789abcdefghijklmnopqrstuvwxyz';
  28. const total = characters.length;
  29. let randomId = '';
  30. for (let i = 0; i < length; i++) {
  31. const random = Math.floor(Math.random() * total);
  32. randomId += characters.charAt(random);
  33. }
  34. return prefix ? `${prefix}-${randomId}` : randomId;
  35. }
  36. interface GetUuidShortOptions {
  37. prefix?: string;
  38. length?: number
  39. }
  40. export { getUuid, getUuidv4, getUuidShort };