-
Notifications
You must be signed in to change notification settings - Fork 181
/
15.deepClone.js
81 lines (63 loc) · 1.65 KB
/
15.deepClone.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const deepClone = (target, cache = new Map()) => {
const isObject = (obj) => typeof obj === 'object' && obj !== null
if (isObject(target)) {
// 解决循环引用
const cacheTarget = cache.get(target)
if (cacheTarget) {
return cacheTarget
}
let cloneTarget = Array.isArray(target) ? [] : {}
cache.set(target, cloneTarget)
for (const key in target) {
const value = target[ key ]
cloneTarget[ key ] = isObject(value) ? deepClone(value, cache) : value
}
return cloneTarget
} else {
return target
}
}
const deepClone2 = (target, cache = new Map()) => {
const isObject = (obj) => typeof obj === 'object' && obj !== null
const forEach = (array, cb) => {
const leng = array.length
let i = -1
while (++i < leng) {
cb(array[ i ])
}
}
if (isObject(target)) {
const cacheObj = cache.get(target)
if (cacheObj) {
return cacheObj
}
let cloneTarget = Array.isArray(target) ? [] : {}
let keys = Object.keys(target)
cache.set(target, cloneTarget)
forEach(keys, (key) => {
const value = target[ key ]
cloneTarget[ key ] = isObject(value) ? deepClone2(value, cache) : value
})
return cloneTarget
} else {
return target
}
}
const target = {
field1: 1,
field2: undefined,
field3: {
child: 'child'
},
field4: [2, 4, 8],
f: { f: { f: { f: { f: { f: { f: { f: { f: { f: { f: { f: {} } } } } } } } } } } },
};
target.target = target;
console.time();
const result1 = deepClone(target);
console.log(result1)
console.timeEnd();
console.time();
const result2 = deepClone2(target);
console.log(result2)
console.timeEnd();