uuid.ts 1.4 KB

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