Skip to content

Commit ef3ebc5

Browse files
committed
feat(kitify): Optimize cloneDeep, add array handling, update cloneLoop
1 parent 7f77053 commit ef3ebc5

File tree

2 files changed

+23
-21
lines changed

2 files changed

+23
-21
lines changed

libs/kitify/src/object/cloneDeep.ts

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
* 深度克隆注意事项:
33
* 1. 支持深度克隆数据
44
* 2. 支持特殊类型数据,如 Map、Set、Date、RegExp、ArrayBuffer、TypedArray、DataView、Symbol 等
5-
* 3. 循环引用处理
6-
* 4. 栈溢出处理
7-
* 5. 性能优化
5+
* 3. 对象属性描述符
6+
* 4. 循环引用处理
7+
* 5. 栈溢出处理
8+
* 6. 性能优化
89
*/
910

1011
/**
@@ -58,6 +59,19 @@ function deepClone<T>(target: T, hash = new WeakMap()): T {
5859
return hash.get(target)
5960
}
6061

62+
// 处理数组
63+
//! 提升判断,优化性能
64+
if (Array.isArray(target)) {
65+
const result: any[] = []
66+
hash.set(target, result)
67+
68+
for (let i = 0, len = target.length; i < len; i++) {
69+
result[i] = deepClone(target[i], hash)
70+
}
71+
72+
return result as any
73+
}
74+
6175
// 处理特殊内置类型: Date, RegExp, ArrayBuffer, TypedArray, DataView, Map, Set
6276
if (target instanceof Date) {
6377
return new Date(target.getTime()) as any
@@ -110,18 +124,6 @@ function deepClone<T>(target: T, hash = new WeakMap()): T {
110124
return result as any
111125
}
112126

113-
// 处理数组
114-
if (Array.isArray(target)) {
115-
const result: any[] = []
116-
hash.set(target, result)
117-
118-
for (let i = 0, len = target.length; i < len; i++) {
119-
result[i] = deepClone(target[i], hash)
120-
}
121-
122-
return result as any
123-
}
124-
125127
// 处理普通对象及其 Symbol 属性
126128
if (typeof target === 'object') {
127129
// 使用 Object.create(Object.getPrototypeOf(target)) 来保留原型链

libs/kitify/src/object/cloneLoop.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ function cloneLoop<T>(value: T): T {
5454
continue
5555
}
5656

57+
// 处理循环引用
58+
if (map.has(sourceValue)) {
59+
target[key] = map.get(sourceValue)
60+
continue
61+
}
62+
5763
// 处理特殊内置类型: Date, RegExp
5864
if (sourceValue instanceof Date) {
5965
target[key] = new Date(sourceValue.getTime())
@@ -64,12 +70,6 @@ function cloneLoop<T>(value: T): T {
6470
continue
6571
}
6672

67-
// 处理循环引用
68-
if (map.has(sourceValue)) {
69-
target[key] = map.get(sourceValue)
70-
continue
71-
}
72-
7373
// 处理数组或对象
7474
const clonedValue = Array.isArray(sourceValue)
7575
? []

0 commit comments

Comments
 (0)