inference.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { isFunction, isObject, isString } from '@vue/shared';
  2. /**
  3. * 检查传入的值是否为undefined。
  4. *
  5. * @param {unknown} value 要检查的值。
  6. * @returns {boolean} 如果值是undefined,返回true,否则返回false。
  7. */
  8. function isUndefined(value?: unknown): value is undefined {
  9. return value === undefined;
  10. }
  11. /**
  12. * 检查传入的值是否为空。
  13. *
  14. * 以下情况将被认为是空:
  15. * - 值为null。
  16. * - 值为undefined。
  17. * - 值为一个空字符串。
  18. * - 值为一个长度为0的数组。
  19. * - 值为一个没有元素的Map或Set。
  20. * - 值为一个没有属性的对象。
  21. *
  22. * @param {T} value 要检查的值。
  23. * @returns {boolean} 如果值为空,返回true,否则返回false。
  24. */
  25. function isEmpty<T = unknown>(value: T): value is T {
  26. if (value === null || value === undefined) {
  27. return true;
  28. }
  29. if (Array.isArray(value) || isString(value)) {
  30. return value.length === 0;
  31. }
  32. if (value instanceof Map || value instanceof Set) {
  33. return value.size === 0;
  34. }
  35. if (isObject(value)) {
  36. return Object.keys(value).length === 0;
  37. }
  38. return false;
  39. }
  40. /**
  41. * 检查传入的字符串是否为有效的HTTP或HTTPS URL。
  42. *
  43. * @param {string} url 要检查的字符串。
  44. * @return {boolean} 如果字符串是有效的HTTP或HTTPS URL,返回true,否则返回false。
  45. */
  46. function isHttpUrl(url?: string): boolean {
  47. if (!url) {
  48. return false;
  49. }
  50. // 使用正则表达式测试URL是否以http:// 或 https:// 开头
  51. const httpRegex = /^https?:\/\/.*$/;
  52. return httpRegex.test(url);
  53. }
  54. /**
  55. * 检查传入的值是否为window对象。
  56. *
  57. * @param {any} value 要检查的值。
  58. * @returns {boolean} 如果值是window对象,返回true,否则返回false。
  59. */
  60. function isWindow(value: any): value is Window {
  61. return (
  62. typeof window !== 'undefined' && value !== null && value === value.window
  63. );
  64. }
  65. /**
  66. * 检查当前运行环境是否为Mac OS。
  67. *
  68. * 这个函数通过检查navigator.userAgent字符串来判断当前运行环境。
  69. * 如果userAgent字符串中包含"macintosh"或"mac os x"(不区分大小写),则认为当前环境是Mac OS。
  70. *
  71. * @returns {boolean} 如果当前环境是Mac OS,返回true,否则返回false。
  72. */
  73. function isMacOs(): boolean {
  74. const macRegex = /macintosh|mac os x/i;
  75. return macRegex.test(navigator.userAgent);
  76. }
  77. /**
  78. * 检查当前运行环境是否为Windows OS。
  79. *
  80. * 这个函数通过检查navigator.userAgent字符串来判断当前运行环境。
  81. * 如果userAgent字符串中包含"windows"或"win32"(不区分大小写),则认为当前环境是Windows OS。
  82. *
  83. * @returns {boolean} 如果当前环境是Windows OS,返回true,否则返回false。
  84. */
  85. function isWindowsOs(): boolean {
  86. const windowsRegex = /windows|win32/i;
  87. return windowsRegex.test(navigator.userAgent);
  88. }
  89. export {
  90. isEmpty,
  91. isFunction,
  92. isHttpUrl,
  93. isMacOs,
  94. isObject,
  95. isString,
  96. isUndefined,
  97. isWindow,
  98. isWindowsOs,
  99. };