/
util.js
65 lines (58 loc) 路 1.24 KB
/
util.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
export function assign(obj, props) {
for (let i in props) obj[i] = props[i];
return obj;
}
export function applyUpdate(state, update) {
if (Array.isArray(state)) {
state = state.slice(0, update.length);
for (let i=0; i<update.length; i++) {
if (update[i]!==undefined) {
state[i] = applyOne(update[i], state[i]);
}
}
}
else {
state = assign({}, state);
for (let i in update) if (update.hasOwnProperty(i)) {
if (update[i]===undefined) {
delete state[i];
}
else {
state[i] = applyOne(update[i], state[i]);
}
}
}
return state;
}
function applyOne(obj, prev) {
if (prev!=null && obj!=null && typeof prev==='object' && typeof obj==='object') {
return applyUpdate(prev, obj);
}
return obj;
}
export function diff(obj, prev) {
let update, i;
if (Array.isArray(obj)) {
update = new Array(obj.length);
for (i=0; i<obj.length; i++) {
if (obj[i]!==prev[i]) {
update[i] = diffOne(obj[i], prev[i]);
}
}
}
else {
update = {};
for (i in obj) {
if (obj.hasOwnProperty(i) && obj[i]!==prev[i]) {
update[i] = diffOne(obj[i], prev[i]);
}
}
}
return update;
}
function diffOne(obj, prev) {
if (typeof obj==='object' && typeof prev==='object') {
return diff(obj, prev);
}
return obj;
}