-
Notifications
You must be signed in to change notification settings - Fork 3
/
diff.ts
374 lines (330 loc) · 9.09 KB
/
diff.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import {
AnyObject,
AnyArray,
ArraySplice,
ObjectPatchNested,
ObjectPatchRemove,
ObjectPatchSet,
ObjectPatch,
ArrayPatchNested,
ArrayPatchSplice,
ArrayPatch,
OuterObjectPatch,
OuterArrayPatch,
OuterPatch,
} from "./types";
/// Fix up some JavaScript types and values that are not JSON.
///
/// This is not a 'deep' fix up, it only touches the immediate value. It's used
/// mainly to ensure diffing checks don't have unexpected results.
///
/// This may still return undefined to signal the value is normally not
/// serialized at all.
const normalizeJson = (val: any): any => {
if (val instanceof Object) {
// Call the `toJSON` method if it exists.
if (typeof val.toJSON === "function") {
val = val.toJSON();
}
}
// Treat functions as undefined.
if (typeof val === "function") {
val = undefined;
} else if (typeof val === "number") {
// Special numbers serialize to null.
if (val !== val || val === Infinity || val === -Infinity) {
val = null;
}
}
return val;
};
/// Diff any two values.
///
/// This is an untyped variant. If you know the value's type, you should use
/// `createObjectPatch` or `createArrayPatch` instead.
export const createPatch = (left: any, right: any): OuterPatch => {
left = normalizeJson(left);
right = normalizeJson(right);
return createPatchNormalized(left, right);
};
/// Diff any two values, already normalized.
const createPatchNormalized = (left: any, right: any): OuterPatch => {
// Treat undefined as null.
if (left === undefined) {
left = null;
}
if (right === undefined) {
right = null;
}
// Identical, don't even need to descend.
if (left === right) {
return "none";
}
const leftIsObject = typeof left === "object" && left !== null;
const rightIsObject = typeof right === "object" && right !== null;
if (leftIsObject && rightIsObject) {
const leftIsArray = Array.isArray(left);
const rightIsArray = Array.isArray(right);
if (leftIsArray && rightIsArray) {
// Descend into two arrays.
return createArrayPatch(left, right);
} else if (!leftIsArray && !rightIsArray) {
// Descend into two regular objects.
return createObjectPatch(left, right);
}
}
// Reset everything else.
return "reset";
};
/// Diff two objects.
export const createObjectPatch = <T extends AnyObject>(
left: T,
right: T
): OuterObjectPatch<T> => {
const r: ObjectPatchRemove<T> = [];
const s: ObjectPatchSet<T> = {};
const p: ObjectPatchNested<T> = {};
let numAttrs = 0;
let numSets = 0;
let numPatches = 0;
// Walk existing properties.
for (const key in left) {
const valLeft = normalizeJson(left[key]);
if (valLeft === undefined) {
continue;
}
numAttrs += 1;
const valRight = normalizeJson(right[key]);
// Attribute was removed.
if (valRight === undefined) {
r.push(key);
continue;
}
// Diff and merge the resulting patch.
const patch = createPatchNormalized(valLeft, valRight);
if (patch === "reset") {
s[key] = valRight;
numSets += 1;
} else if (patch !== "none") {
p[key] = patch;
numPatches += 1;
}
}
// No partial changes, tell parent we should be reset.
if (numAttrs && r.length + numSets === numAttrs) {
return "reset";
}
// Find new properties.
for (const key in right) {
const valRight = normalizeJson(right[key]);
if (valRight === undefined) {
continue;
}
// Attributes was added to an empty object.
if (numAttrs === 0) {
return "reset";
}
// Attribute was added.
const valLeft = normalizeJson(left[key]);
if (valLeft === undefined) {
s[key] = valRight;
numSets += 1;
}
}
// Build the patch object.
const res: ObjectPatch<T> = { t: "o" };
if (r.length) {
res.r = r;
}
if (numSets) {
res.s = s;
}
if (numPatches) {
res.p = p;
}
if (!res.r && !res.s && !res.p) {
return "none";
} else {
return res;
}
};
// Compare two arrays.
export const createArrayPatch = <T extends AnyArray>(
left: T,
right: T
): OuterArrayPatch<T> => {
const lenLeft = left.length;
const lenRight = right.length;
let valLeft, valRight, idx;
// Reduce the problem by trimming exact matches at the start.
let start, firstDiff;
for (start = 0; start < lenLeft && start < lenRight; start += 1) {
const valLeft = normalizeJson(left[start]);
const valRight = normalizeJson(right[start]);
firstDiff = createPatchNormalized(valLeft, valRight);
if (firstDiff !== "none") {
break;
}
}
// Short-circuit for exact matches, pushes and pops.
if (start === lenLeft) {
if (start === lenRight) {
return "none";
}
const splice: ArraySplice<T> = [
lenLeft,
0,
...right.slice(start, lenRight).map(normalizeJson),
];
return { t: "a", s: [splice] };
} else if (start === lenRight) {
const splice: ArraySplice<T> = [start, lenLeft - start];
return { t: "a", s: [splice] };
}
// Reduce further by trimming exact matches at the end.
let endLeft = lenLeft - 1;
let endRight = lenRight - 1;
let lastDiff;
while (endLeft >= start && endRight >= start) {
valLeft = normalizeJson(left[endLeft]);
valRight = normalizeJson(right[endRight]);
lastDiff = createPatchNormalized(valLeft, valRight);
if (lastDiff !== "none") {
break;
}
endLeft -= 1;
endRight -= 1;
}
// Short-circuit for a single block of inserts or removes.
if (endLeft < start) {
const splice: ArraySplice<T> = [
start,
0,
...right.slice(start, endRight + 1).map(normalizeJson),
];
return { t: "a", s: [splice] };
} else if (endRight < start) {
const splice: ArraySplice<T> = [start, endLeft - start + 1];
return { t: "a", s: [splice] };
}
// For the remainder, do a full search. This implements the greedy
// algorithm described in Myers' paper: http://xmailserver.org/diff2.pdf
// FIXME: Look into the refinements described in the paper.
const width = endLeft - start + 1;
const height = endRight - start + 1;
const size = width * height;
const diag = width + 1;
const diffs = new Array(size);
diffs[0] = firstDiff;
diffs[size - 1] = lastDiff;
let v, d, k, x, y, diff;
v = { 1: 0 }; // sentinel
outer: for (d = 0; d < size; d++) {
v = Object.create(v);
for (k = -d; k <= d; k += 2) {
// Decide on direction.
if (k === -d || (k !== d && v[k - 1] < v[k + 1])) {
x = v[k + 1];
} else {
x = v[k - 1] + 1;
}
y = x - k;
// Exhaust diagonal until we hit a reset.
idx = y * width + x;
while (idx < size && x < width && y < height) {
diff = diffs[idx];
if (!diff) {
valLeft = normalizeJson(left[start + x]);
valRight = normalizeJson(right[start + y]);
diff = diffs[idx] = createPatchNormalized(valLeft, valRight);
}
if (diff === "reset") {
break;
}
x++;
y++;
idx += diag;
}
v[k] = x;
if (x >= width && y >= height) {
break outer;
}
}
}
// Collect patches and splices.
let havePatches = false;
const p: ArrayPatchNested<T> = {};
const s: ArrayPatchSplice<T> = [];
if (d === size) {
if (start === 0 && width === lenLeft) {
// If we splice the entire array, return a reset.
return "reset";
} else {
// If we have no diagonals, we can optimize.
s.push([start, width, ...right.slice(start, endRight + 1)]);
}
} else {
k = width - height;
let current: ArraySplice<T> = [NaN, NaN];
while (d-- >= 0) {
// Decide on direction.
const isVert: boolean =
v[k - 1] === undefined ||
(v[k + 1] !== undefined && v[k - 1] < v[k + 1]);
k = isVert ? k + 1 : k - 1;
x = v[k];
y = x - k;
// Append the move to the current splice, or create a new one.
// The `y !== -1` check skips the sentinel.
const idxLeft = start + x;
if (isVert) {
// element added
if (y !== -1) {
if (current[0] === idxLeft) {
valRight = normalizeJson(right[start + y]);
current.splice(2, 0, valRight);
} else {
s.push((current = [idxLeft, 0, right[start + y]]));
}
}
y++;
} else {
// element removed
if (y !== -1) {
if (current[0] === idxLeft + 1) {
current[0] -= 1;
current[1] += 1;
} else {
s.push((current = [idxLeft, 1]));
}
}
x++;
}
// Exhaust diagonal until we hit a reset.
idx = y * width + x;
while (idx < size && x < width && y < height) {
diff = diffs[idx];
if (diff === "reset") {
break;
}
if (diff !== "none") {
p[start + x] = diff;
havePatches = true;
}
x++;
y++;
idx += diag;
}
v = Object.getPrototypeOf(v);
}
}
// Build the patch object.
const res: ArrayPatch<T> = { t: "a" };
if (havePatches) {
res.p = p;
}
if (s.length) {
res.s = s;
}
return res;
};