-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone-deep.mjs
More file actions
30 lines (27 loc) · 732 Bytes
/
Copy pathclone-deep.mjs
File metadata and controls
30 lines (27 loc) · 732 Bytes
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
const target = {
field1: 1,
field2: undefined,
field3: {
child: 'child'
},
field4: [2, 4, 8]
};
target.target2 = target;
function cloneDeep(target, map = new WeakMap()) {
if (typeof target === 'object') {
const cloneTarget = Array.isArray(target) ? [] : {}
const currentTarget = map.get(target);
if (currentTarget) {
return currentTarget;
}
map.set(target, cloneTarget)
for (const key in target) {
cloneTarget[key] = cloneDeep(target[key], map);
}
return cloneTarget;
}
return target;
}
const newTarget = cloneDeep(target);
// const newTarget = target;
console.log(target.field4 === newTarget.field4);