feat:封装公共工具函数

This commit is contained in:
fangyunong 2025-07-13 11:10:24 +08:00
parent 4ef3ad8d3f
commit f4bdfb9484

View File

@ -1,4 +1,28 @@
// 深拷贝
export function deepClone(){
// 对象深拷贝 obj 对象
export function deepClone<T>(obj: T): T {
if (obj === null || typeof obj !== "object") return obj;
if (obj instanceof Date) return new Date(obj.getTime()) as unknown as T;
if (obj instanceof RegExp) return new RegExp(obj) as unknown as T;
const clone: any = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
// 字典value转label
interface DictItem<T> {
value: T;
label: string;
}
export function dictTransform<T, K extends DictItem<T>>(
value: T,
dict: K[]
): string | T {
if (!dict || !Array.isArray(dict)) throw new Error("字典必须为一个数组对象");
if (value === undefined || value === null) throw new Error("请传入字段值");
const foundItem = dict.find((item) => item.value === value);
return foundItem ? foundItem.label : dict[0]?.label || "";
}