getUuid.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. export function uuid(len = 5, radix = 62) {
  2. const chars =
  3. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  4. let uuid = [],
  5. i;
  6. radix = radix || chars.length;
  7. if (len) {
  8. // Compact form
  9. for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  10. } else {
  11. // rfc4122, version 4 form
  12. let r;
  13. // rfc4122 requires these characters
  14. uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
  15. uuid[14] = "4";
  16. // Fill in random data. At i==19 set the high bits of clock sequence as
  17. // per rfc4122, sec. 4.1.5
  18. for (i = 0; i < 36; i++) {
  19. if (!uuid[i]) {
  20. r = 0 | (Math.random() * 16);
  21. uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
  22. }
  23. }
  24. }
  25. return uuid.join("");
  26. }
  27. export function generateRandomString(length: number = 10): string {
  28. let result: string = "";
  29. let characters: string =
  30. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  31. let charactersLength: number = characters.length;
  32. for (let i: number = 0; i < length; i++) {
  33. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  34. }
  35. return result;
  36. }