forked from emberjs/data
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdeep-copy.js
54 lines (42 loc) · 1.19 KB
/
deep-copy.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
/* global WeakMap */
export default function deepCopy(obj) {
return _deepCopy(obj, new WeakMap());
}
function isPrimitive(value) {
return typeof value !== 'object' || value === null;
}
function _deepCopy(oldObject, seen) {
if (Array.isArray(oldObject)) {
return copyArray(oldObject, seen);
} else if (!isPrimitive(oldObject)) {
return copyObject(oldObject, seen);
} else {
return oldObject;
}
}
function copyObject(oldObject, seen) {
let newObject = {};
Object.keys(oldObject).forEach(key => {
let value = oldObject[key];
let newValue = isPrimitive(value) ? value : seen.get(value);
if (value && newValue === undefined) {
newValue = newObject[key] = _deepCopy(value, seen);
seen.set(value, newValue);
}
newObject[key] = newValue;
});
return newObject;
}
function copyArray(oldArray, seen) {
let newArray = [];
for (let i = 0; i < oldArray.length; i++) {
let value = oldArray[i];
let newValue = isPrimitive(value) ? value : seen.get(value);
if (value && newValue === undefined) {
newValue = newArray[i] = _deepCopy(value, seen);
seen.set(value, newValue);
}
newArray[i] = newValue;
}
return newArray;
}