-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtrackForMutations.js
77 lines (65 loc) · 1.86 KB
/
trackForMutations.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
export default function trackForMutations(isImmutable, ignore, obj) {
const trackedProperties = trackProperties(isImmutable, ignore, obj);
return {
detectMutations() {
return detectMutations(isImmutable, ignore, trackedProperties, obj);
}
};
}
function trackProperties(isImmutable, ignore = [], obj, path = []) {
const tracked = { value: obj };
if (!isImmutable(obj)) {
tracked.children = {};
for (const key in obj) {
const childPath = path.concat(key);
if (ignore.length && ignore.indexOf(childPath.join('.')) !== -1) {
continue;
}
tracked.children[key] = trackProperties(
isImmutable,
ignore,
obj[key],
childPath
);
}
}
return tracked;
}
function detectMutations(isImmutable, ignore = [], trackedProperty, obj, sameParentRef = false, path = []) {
const prevObj = trackedProperty ? trackedProperty.value : undefined;
const sameRef = prevObj === obj;
if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
return { wasMutated: true, path };
}
if (isImmutable(prevObj) || isImmutable(obj)) {
return { wasMutated: false };
}
// Gather all keys from prev (tracked) and after objs
const keysToDetect = {};
Object.keys(trackedProperty.children).forEach(key => {
keysToDetect[key] = true;
});
Object.keys(obj).forEach(key => {
keysToDetect[key] = true;
});
const keys = Object.keys(keysToDetect);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const childPath = path.concat(key);
if (ignore.length && ignore.indexOf(childPath.join('.')) !== -1) {
continue;
}
const result = detectMutations(
isImmutable,
ignore,
trackedProperty.children[key],
obj[key],
sameRef,
childPath
);
if (result.wasMutated) {
return result;
}
}
return { wasMutated: false };
}