random.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const hexList: string[] = []
  2. for (let i = 0; i <= 15; i++) {
  3. hexList[i] = i.toString(16)
  4. }
  5. /**
  6. * 生成随机数
  7. * @param min 最小值
  8. * @param max 最大值
  9. * @returns 生成的随机数
  10. */
  11. export function randomNum(min: number, max: number) {
  12. switch (arguments.length) {
  13. case 1:
  14. return parseInt((Math.random() * min + 1).toString(), 10)
  15. break
  16. case 2:
  17. return parseInt((Math.random() * (max - min + 1) + min).toString(), 10)
  18. break
  19. default:
  20. return 0
  21. break
  22. }
  23. }
  24. /**
  25. * 生成全球唯一标识
  26. * @returns uuid
  27. */
  28. export function uuid(): string {
  29. let uuid = ''
  30. for (let i = 1; i <= 36; i++) {
  31. if (i === 9 || i === 14 || i === 19 || i === 24) {
  32. uuid += '-'
  33. } else if (i === 15) {
  34. uuid += 4
  35. } else if (i === 20) {
  36. uuid += hexList[(Math.random() * 4) | 8]
  37. } else {
  38. uuid += hexList[(Math.random() * 16) | 0]
  39. }
  40. }
  41. return uuid
  42. }
  43. /**
  44. * 生成唯一标识
  45. * @param prefix 前缀
  46. * @returns 唯一标识
  47. */
  48. export function shortUuid(prefix = ''): string {
  49. const time = Date.now()
  50. const random = Math.floor(Math.random() * 1000000000)
  51. if (!window.unique) window.unique = 0
  52. window.unique++
  53. return prefix + '_' + random + window.unique + String(time)
  54. }