-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepcopy.ts
More file actions
61 lines (53 loc) · 1.26 KB
/
Copy pathdeepcopy.ts
File metadata and controls
61 lines (53 loc) · 1.26 KB
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
export function deepCopy(object: any) {
var cachedItems = [];
function copy(obj: any) {
if (!(obj instanceof Object)) {
return obj;
}
// repeat objects, circular reference
for (let item of cachedItems) {
if (item.source === obj) {
return item.target
}
}
let newObj = {}
cachedItems.push({ source: obj, target: newObj })
// recursion copy
for (let key of Object.getOwnPropertyNames(obj)) {
newObj[key] = copy(obj[key])
}
// console.log(cachedItems, obj)
return newObj
}
return copy(object)
}
//
var a = { b: 1, w: { ww: 0 } }
var c = { d: a, e: 2, f: { g: 3, h: { i: 4 }, a } }
c.f.h['j'] = c;
var copyC = deepCopy(c)
console.log(c)
console.log(copyC)
a.b = 6; c.f.h.i = 8;
console.log(c.f.h['j'])
console.log(copyC.f.h['j'])
//
export function shallowCopy(obj: any) {
if (obj instanceof Object) {
let newObj = {}
for (let key of Object.getOwnPropertyNames(obj)) {
newObj[key] = obj[key]
}
return newObj
} else {
return obj
}
}
// var a = { b: 1 }, f = { g: 3, h: { i: 4, c }, a }
// var c = { d: a, e: 2, f }
// var shallowCopyC = shallowCopy(c)
// console.log(c)
// console.log(shallowCopyC)
// c.e = 7; a.b = 8;
// console.log(c)
// console.log(shallowCopyC)