/** url地址相关工具 */ export const url = { /** * 将对象转换为url参数形式,支持忽略指定字段 * @param obj { x: 1, y: 2, z: 3 } * @param ignoreFields ['z'] * @returns x=1&y=2 */ objToUrlParma: (obj: Record, ignoreFields: Array = []): string => { return ( '?' + Object.keys(obj) .filter((key) => ignoreFields.indexOf(key) === -1) .map((key) => `${key}=${obj[key]}`) .join('&') ); }, /** * 获取url参数对象 * @param url {string} 完整url,默认当前页面url * @returns {Record} { x: 1, y: 2, z: 3 } */ getUrlToParams: (url: string = window.location.href): Record => { const urlParams = new URLSearchParams(url.split('?')[1]); const params = {}; for (const [key, value] of urlParams.entries()) { params[key] = value; } return params; }, }; /** route路由相关工具 */ export const route = { FILE_NAME_PREFIX: '/src/views', convertPathToName: (path: string): string => { return path .split('/') // 分割路径 .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) // 首字母大写 .join(''); // 连接成字符串 }, getTitleFromPathStr: (arr: any, path: string): string => { const item = arr.find(({ key }) => path.includes(key)); return item ? item.title : path; // 如果找到,返回 title;否则返回 null }, }; /** 数组相关工具 */ export const array = { /** * 判断两个数组是否相等,只递归一层,如果有嵌套数组或对象,则只判断第一层,并且永远不相等 * 支持忽略指定字段 * [{ a:1, b:2 }, { c:3, d:4 }] 比较 [{ a:1, b:2 }, { c:3, d:4 }] 结果为 true * [{ a:1, b:2 }, { c:3, d:4 }] 比较 [{ a:1, b:2 }, { c:3, d:5 }] 结果为 false * [{ a:1, b: { b1: 1 }}, { c:3, d:4 }] 比较 [{ a:1, b: { b1: 1 }}, { c:3, d:4 }] 结果为false,因为b是对象,只比较第一层 * @param arr1 * @param arr2 * @param ignoreFields ['a', 'b'] * @returns boolean */ arraysAreEqual: (arr1: any[], arr2: any[], ignoreFields: Array = []): boolean => { if (arr1.length !== arr2.length) { return false; } return arr1.every((item, index) => { const item2 = arr2[index]; if (typeof item === 'object' && typeof item2 === 'object') { return Object.keys(item) .filter((key) => ignoreFields.indexOf(key) === -1) .every((key) => item[key] === item2[key]); } else { return item === item2; } }); }, }; export const generateUUID = () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); }; /** 获取远程资源markdown内的内容 */ export const getMarkdownContent = (filePath) => { return new Promise((resolve, reject) => { fetch(filePath, { method: 'GET', }) .then((result) => { result .text() .then((res) => { resolve(res); }) .catch((err) => reject(err)); }) .catch((err) => reject(err)); }); };