0%

ts手写工具函数

防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
export function debounce<T extends (...args: any[]) => void>(
fn: T,
delay: number
): (...args: Parameters<T>) => void {
let timer: ReturnType<typeof setTimeout> | null = null;

return function (...args: Parameters<T>) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delay);
};
}

节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function throttle<T extends (...args: any[]) => void>(
fn: T,
wait: number
): (...args: Parameters<T>) => void {
let lastTime = 0;

return function (...args: Parameters<T>) {
const now = Date.now();
if (now - lastTime >= wait) {
lastTime = now;
fn(...args);
}
};
}

深拷贝 deepClone

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export function deepClone<T>(target: T, map = new WeakMap()): T {
// 基础类型或函数直接返回
if (typeof target !== 'object' || target === null) return target;

// 已处理过的对象,直接返回以防循环引用
if (map.has(target)) return map.get(target);

let clone: any;

const Constructor = (target as any).constructor;
switch (Constructor) {
case Date:
clone = new Date((target as unknown as Date).getTime());
break;
case RegExp:
clone = new RegExp((target as unknown as RegExp).source, (target as unknown as RegExp).flags);
break;
case Map:
clone = new Map();
map.set(target, clone);
(target as unknown as Map<any, any>).forEach((value, key) => {
clone.set(deepClone(key, map), deepClone(value, map));
});
return clone;
case Set:
clone = new Set();
map.set(target, clone);
(target as unknown as Set<any>).forEach((value) => {
clone.add(deepClone(value, map));
});
return clone;
default:
clone = Array.isArray(target) ? [] : {};
map.set(target, clone);
for (const key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
clone[key] = deepClone((target as any)[key], map);
}
}
return clone;
}

map.set(target, clone);
return clone;
}