uuid.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. return crypto.randomUUID();
  8. } catch (err) {
  9. return getUuid('semi');
  10. }
  11. }
  12. /**
  13. * Get a random id with prefix, it not strictly guarantee id uniqueness
  14. *
  15. * Note: the return value of getUuid is too long, we need a short one
  16. *
  17. * @example
  18. * getUuidShort({ prefix: 'semi' }) => 'semi-46dinzc'
  19. * getUuidShort({ prefix: '' }) => '0eer2i0'
  20. * getUuidShort({ prefix: 'semi', length: 4 }) => 'semi-8jts'
  21. */
  22. function getUuidShort(options: GetUuidShortOptions = {}) {
  23. const { prefix = '', length = 7 } = options;
  24. const characters = '0123456789abcdefghijklmnopqrstuvwxyz';
  25. const total = characters.length;
  26. let randomId = '';
  27. for (let i = 0; i < length; i++) {
  28. const random = Math.floor(Math.random() * total);
  29. randomId += characters.charAt(random);
  30. }
  31. return prefix ? `${prefix}-${randomId}` : randomId;
  32. }
  33. interface GetUuidShortOptions {
  34. prefix?: string;
  35. length?: number;
  36. }
  37. export { getUuid, getUuidv4, getUuidShort };