Skip to content

Commit

Permalink
feat(kitify): Optimize cloneDeep, add array handling, update cloneLoop
Browse files Browse the repository at this point in the history
  • Loading branch information
Marinerer committed Dec 26, 2024
1 parent 7f77053 commit ef3ebc5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 21 deletions.
32 changes: 17 additions & 15 deletions libs/kitify/src/object/cloneDeep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
* 深度克隆注意事项:
* 1. 支持深度克隆数据
* 2. 支持特殊类型数据,如 Map、Set、Date、RegExp、ArrayBuffer、TypedArray、DataView、Symbol 等
* 3. 循环引用处理
* 4. 栈溢出处理
* 5. 性能优化
* 3. 对象属性描述符
* 4. 循环引用处理
* 5. 栈溢出处理
* 6. 性能优化
*/

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

// 处理数组
//! 提升判断,优化性能
if (Array.isArray(target)) {
const result: any[] = []
hash.set(target, result)

for (let i = 0, len = target.length; i < len; i++) {
result[i] = deepClone(target[i], hash)
}

return result as any
}

// 处理特殊内置类型: Date, RegExp, ArrayBuffer, TypedArray, DataView, Map, Set
if (target instanceof Date) {
return new Date(target.getTime()) as any
Expand Down Expand Up @@ -110,18 +124,6 @@ function deepClone<T>(target: T, hash = new WeakMap()): T {
return result as any
}

// 处理数组
if (Array.isArray(target)) {
const result: any[] = []
hash.set(target, result)

for (let i = 0, len = target.length; i < len; i++) {
result[i] = deepClone(target[i], hash)
}

return result as any
}

// 处理普通对象及其 Symbol 属性
if (typeof target === 'object') {
// 使用 Object.create(Object.getPrototypeOf(target)) 来保留原型链
Expand Down
12 changes: 6 additions & 6 deletions libs/kitify/src/object/cloneLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ function cloneLoop<T>(value: T): T {
continue
}

// 处理循环引用
if (map.has(sourceValue)) {
target[key] = map.get(sourceValue)
continue
}

// 处理特殊内置类型: Date, RegExp
if (sourceValue instanceof Date) {
target[key] = new Date(sourceValue.getTime())
Expand All @@ -64,12 +70,6 @@ function cloneLoop<T>(value: T): T {
continue
}

// 处理循环引用
if (map.has(sourceValue)) {
target[key] = map.get(sourceValue)
continue
}

// 处理数组或对象
const clonedValue = Array.isArray(sourceValue)
? []
Expand Down

0 comments on commit ef3ebc5

Please sign in to comment.