-
-
Notifications
You must be signed in to change notification settings - Fork 361
/
deep_copy.ts
76 lines (62 loc) · 1.67 KB
/
deep_copy.ts
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
export default function deep_copy<T> (obj: T, refs = new Set()): T {
let copy: any;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = obj.map((i) => deep_copy(i, refs));
return copy;
}
// Handle Set
if (obj instanceof Set) {
copy = new Set(obj);
return copy;
}
// Handle Map
if (obj instanceof Map) {
copy = new Map(obj);
return copy;
}
// Handle Buffer
if (obj instanceof Buffer) {
copy = Buffer.from(obj);
return copy;
}
// Handle Uint8Array
if (obj instanceof Uint8Array) {
copy = new Uint8Array(obj);
return copy;
}
if (obj instanceof Function) {
// This is not technically correct, but required for unit test purposes. We currently have a unit test that passes in a function where it shouldn't. So in order to handle this case we need to do something here. Ideally we would clone the function somehow to create a copy of it. But that is lower priority for now.
return obj;
}
// Handle Object
if (obj instanceof Object) {
refs.add(obj);
if (obj.constructor !== Object) {
copy = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
} else {
copy = {};
}
for (const attr in obj) {
if (Object.prototype.hasOwnProperty.call(obj, attr)) {
const value = obj[attr];
const isObjValue = typeof value === "object" && !Array.isArray(value) && value !== null;
if (isObjValue) {
const isCircular = refs.has(value);
// Omit circular property from copy
if (isCircular) continue;
refs.add(value);
}
copy[attr] = deep_copy(obj[attr], refs);
}
}
return copy;
}
return obj;
}