index.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. function isObject(value: any) {
  2. return typeof value === 'object' && !Array.isArray(value)
  3. }
  4. // 比较两个对象,并提取出不同的部分
  5. function getTwoObjectDiff(originalObj: Record<string, any>, diffObj: Record<string, any>): Record<any, string> {
  6. if (!isObject(originalObj) || !isObject(diffObj)) {
  7. return diffObj
  8. }
  9. const diff: Record<string, any> = {}
  10. for (const key in diffObj) {
  11. const originalValue = originalObj[key]
  12. const diffValue = diffObj[key]
  13. if (JSON.stringify(originalValue) !== JSON.stringify(diffValue)) {
  14. if (isObject(originalValue) && isObject(diffValue)) {
  15. const nestedDiff = getTwoObjectDiff(originalValue, diffValue)
  16. if (Object.keys(nestedDiff).length > 0) {
  17. diff[key] = nestedDiff
  18. }
  19. }
  20. else {
  21. diff[key] = diffValue
  22. }
  23. }
  24. }
  25. return diff
  26. }
  27. /**
  28. * 在指定范围内生成指定数量的随机整数
  29. * @param count 指定数量
  30. * @param max 指定范围
  31. *
  32. * 示例: 生成10以内的4个随机整数
  33. * let randomNumbers = generateRandomNumbers(4, 10)
  34. */
  35. function generateRandomNumbers(count: number, max: number): number[] {
  36. const numbers = new Set()
  37. while (numbers.size < count) {
  38. numbers.add(Math.floor(Math.random() * max) + 1)
  39. }
  40. return Array.from(numbers) as number[]
  41. }
  42. /**
  43. * 毫秒数转时分秒
  44. * @param fmtSeconds
  45. */
  46. function formatSeconds(fmtSeconds: number): string {
  47. const hours = Math.floor(fmtSeconds / (1000 * 60 * 60))
  48. const minutes = Math.floor((fmtSeconds % (1000 * 60 * 60)) / (1000 * 60))
  49. const seconds = Math.floor((fmtSeconds % (1000 * 60)) / 1000)
  50. if (hours === 0) {
  51. if (hours === 0 && minutes === 0) {
  52. return `${seconds.toString().padStart(2, '0')}秒`
  53. }
  54. else {
  55. return `${minutes.toString().padStart(2, '0')}分 ${seconds.toString().padStart(2, '0')}秒`
  56. }
  57. }
  58. return `${hours.toString().padStart(2, '0')}时 ${minutes.toString().padStart(2, '0')}分 ${seconds.toString().padStart(2, '0')}秒`
  59. }
  60. function isAndroidOrIos(): 'android' | 'ios' | 'unknown' {
  61. const userAgent = navigator.userAgent.toLowerCase()
  62. if (/iphone|ipad|ipod/.test(userAgent)) {
  63. return 'ios'
  64. }
  65. else if (/android/.test(userAgent)) {
  66. return 'android'
  67. }
  68. return 'unknown'
  69. }
  70. export {
  71. getTwoObjectDiff,
  72. generateRandomNumbers,
  73. formatSeconds,
  74. isAndroidOrIos,
  75. }