68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
/**
|
|
* 工具函数集合
|
|
* 包含字段处理、防抖等通用功能
|
|
*/
|
|
|
|
/**
|
|
* 处理字段名,去除类型后缀
|
|
* 例如: "字段名_类型" -> "字段名"
|
|
*/
|
|
export function processFieldName(field: string): string {
|
|
if (field.includes('_')) {
|
|
return field.split('_')[0]; // 只保留类型前面的字段名
|
|
}
|
|
return field;
|
|
}
|
|
|
|
/**
|
|
* 处理字段数组,去除类型后缀并去重
|
|
*/
|
|
export function processFieldNames(fields: string[]): string[] {
|
|
// 处理字段,去掉类型后缀
|
|
const processedFields = fields.map(processFieldName);
|
|
|
|
// 去重并返回
|
|
return [...new Set(processedFields)];
|
|
}
|
|
|
|
/**
|
|
* 创建防抖函数
|
|
* @param fn 要执行的函数
|
|
* @param delay 延迟时间(毫秒)
|
|
*/
|
|
export function debounce<T extends (...args: unknown[]) => unknown>(
|
|
fn: T,
|
|
delay: number
|
|
): (...args: Parameters<T>) => void {
|
|
let timer: NodeJS.Timeout | null = null;
|
|
|
|
return function(...args: Parameters<T>) {
|
|
if (timer) {
|
|
clearTimeout(timer);
|
|
}
|
|
|
|
timer = setTimeout(() => {
|
|
fn(...args);
|
|
timer = null;
|
|
}, delay);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 比较两个数组是否有实质性不同
|
|
* 用于避免不必要的状态更新
|
|
*/
|
|
export function areArraysDifferent<T>(arr1: T[], arr2: T[]): boolean {
|
|
return JSON.stringify(arr1) !== JSON.stringify(arr2);
|
|
}
|
|
|
|
/**
|
|
* 查找两个数组之间的差异项
|
|
* @returns 包含新增和删除项的对象
|
|
*/
|
|
export function getArrayDifference<T>(current: T[], previous: T[]): { added: T[], removed: T[] } {
|
|
const added = current.filter(item => !previous.includes(item));
|
|
const removed = previous.filter(item => !current.includes(item));
|
|
|
|
return { added, removed };
|
|
}
|