-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJSON-Diff.js
479 lines (395 loc) · 14.4 KB
/
JSON-Diff.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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
var applyPatches = require('./lib/applyPatches');
var unchangedArea = require('./lib/unchangedArea.js');
var patchArea = require('./lib/patchArea.js');
var hashObject = require('./lib/hashObject.js');
exports.diff = diff;
exports.apply = apply;
// browserify -s jdr -e JSON-Diff.js -o json-diff-rfc6902.js
var OBJ_COM = true;
var ARR_COM = true;
var HASH_ID = null;
function apply(app_old, jpn_patch) {
applyPatches.apply(app_old, jpn_patch);
}
function diff(oldJson, newJson, options) {
// Initial
if(typeof options === 'object') {
if(options.OBJ_COM !== void 0) {OBJ_COM = options.OBJ_COM;}
if(options.ARR_COM !== void 0) {ARR_COM = options.ARR_COM;}
if(options.HASH_ID !== void 0) {HASH_ID = options.HASH_ID;}
}
// check the input value
if (oldJson === undefined || newJson === undefined) {
throw new Error("Invalid input: A JSON value can be an object, array, number, string, true, false, or null.");
}
// Get the unchanged area
var unchanged = [];
if (OBJ_COM === true) {
unchangedArea.generateUnchanged(oldJson, newJson, unchanged, '');
}
// Generate the diff
var patches = [];
generateDiff(oldJson, newJson, unchanged, patches, '');
patchArea.handlePatch(patches);
return patches;
}
function generateDiff(oldJson, newJson, unchanged, patches, path) {
// check the input value
if (oldJson === undefined || newJson === undefined) {
throw new Error("Invalid input: A JSON value can be an object, array, number, string, true, false, or null.");
}
// var a = null object Array.isArray: false
// var a = 5 number
// var a = [1,2] object Array.isArray: true
// var a undefined Array.isArray: false
if (Array.isArray(oldJson) && Array.isArray(newJson)) {
generateArrayDiff(oldJson, newJson, unchanged, patches, path);
return;
}
if (typeof oldJson === "object" && oldJson !== null && typeof newJson === "object" && newJson !== null) {
generateObjectDiff(oldJson, newJson, unchanged, patches, path);
return;
}
return generateValueDiff(oldJson, newJson, unchanged, patches, path);
}
function generateValueDiff(oldJson, newJson, unchanged, patches, path) {
// the endpoint
if (newJson !== oldJson) {
patches.push({ op: "replace", path: path, value: newJson});
}
}
function generateArrayDiff(oldJson, newJson, unchanged, patches, path) {
// console.log("--------This is Array-------------");
// x, y is the hash of json
// var x = hashObject.map(hashObject.hash, oldJson);
// var y = hashObject.map(hashObject.hash, newJson);
if (oldJson.length === 0 && newJson.length ===0 ) {return;}
// Use LCS
var tmpPatches = [];
var tmpPatchHashes = [];
if (oldJson.length === 0) {
patches.push({ op: "add", path: path, value: newJson});
} else {
// Use sortBack
tmpPatches = transformArray(oldJson, newJson, unchanged, tmpPatches, tmpPatchHashes, path);
for (var l = 0; l < tmpPatches.length; l++) {
patches.push(tmpPatches[l]);
}
}
}
function generateObjectDiff(oldJson, newJson, unchanged, patches, path) {
var oldKeys = Object.keys(oldJson);
var newKeys = Object.keys(newJson);
var removed = false;
var oldKey, oldValue;
// Loop from the old; from lengths -1 to 0
for (var i = oldKeys.length -1; i >= 0; i--) {
oldKey = oldKeys[i];
oldValue = oldJson[oldKey];
// check the value
if (oldValue === undefined) {
throw new Error("Invalid input: A JSON value can be an object, array, number, string, true, false, or null.");
}
if (newJson.hasOwnProperty(oldKey)) {
// go deeper
generateDiff(oldJson[oldKey], newJson[oldKey], unchanged, patches, path + "/" + oldKey);
} else {
// Remove
removed = true;
patches.push({ op: "remove", path: path + "/" + patchPointString(oldKey), value: oldValue });
}
}
// If doesn't remove and the length is the same, return
// Return: only the length is equal and doesn't remove
if (!removed && newKeys.length === oldKeys.length) { return; }
// Loop from the new
// length is not the same
var newKey;
var newVal;
for (var j = 0; j < newKeys.length; j ++) {
newKey = newKeys[j];
newVal = newJson[newKey];
// check the value
if (newVal === undefined) {
throw new Error("Invalid input: A JSON value can be an object, array, number, string, true, false, or null.");
}
if (!oldJson.hasOwnProperty(newKey)) {
//Try to find the value in the unchanged area
// change JSON.stringify()
var pointer = unchangedArea.findValueInUnchanged(JSON.stringify(newVal), unchanged);
if (pointer) {
//COPY
patches.push({ op: "copy", path: path + "/" + patchPointString(newKey), from: pointer});
} else {
// no json.stringnify
var previousIndex = -1;
if (OBJ_COM === true) {
previousIndex = patchArea.findValueInPatch(newVal, patches);
}
if (previousIndex !== -1 && patches[previousIndex].op === 'remove') {
// MOVE
var oldPath = patches[previousIndex].path;
patches.splice(previousIndex, 1);
patches.push({ op: "move", from: oldPath, path: path + "/" + patchPointString(newKey)});
} else {
//ADD
patches.push({ op: "add", path: path + "/" + patchPointString(newKey), value: newVal});
}
}
}
}
}
function patchPointString(str) {
// According to RFC 6901
// '~' needs to be encoded as '~0'
// '/' needs to be encoded as '~1'
if (str.indexOf('/') === -1 && str.indexOf('~') === -1) {
return str;
}
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function transformIndex(element, m, array) {
var finalIndex;
switch(element.op) {
case 'add':
case 'replace':
case 'copy':
// When add, replace and copy, add directly
return element.index;
case 'remove':
finalIndex = element.index;
break;
case 'move':
finalIndex = element.from;
break;
}
for (var i = 0; i < m; i++) {
switch (array[i].op) {
case 'remove':
if(finalIndex > array[i].index) {
// when equal, don't --
finalIndex --;
}
break;
case 'add':
case 'copy':
if(finalIndex >= array[i].index) {
// when equal, do ++
finalIndex ++;
}
break;
case 'replace':
// when equal, don't change
break;
case 'move':
if (array[i].from !== array[i].index) {
var min = Math.min(array[i].from, array[i].index);
var max = Math.max(array[i].from, array[i].index);
if (finalIndex >= min && finalIndex <= max) {
if (array[i].from > array[i].index) {
finalIndex ++;
} else {
finalIndex --;
}
}
}
break;
}
}
return finalIndex;
}
function operationValue (op) {
switch (op) {
case "move" : return 0;
case "remove" : return 1;
case "add" : return 2;
case "replace": return 3;
case "copy" : return 4;
}
}
function compare(a, b) {
if (a.index === b.index) {
// Order: move < remove < add
var a_value = operationValue(a.op);
var b_value = operationValue(b.op);
if (a_value > b_value) {
return 1;
} else {
return -1;
}
} else {
return a.index - b.index;
}
}
function findCopyInArray(element, m, array, arrUnchanged) {
var copyIndex = -1;
for (var i = 0; i < m; i++) {
switch (element.op) {
case 'remove':
case 'copy':
break;
default:
// Move Replace Add
if (element.hash === array[i].hash) {
return array[i].index;
}
break;
}
}
//Find value in arrUnchanged
for (var j= 0; j< arrUnchanged.length; j++) {
if (element.hash === arrUnchanged[j].hash) {
return arrUnchanged[j].index;
}
}
return copyIndex;
}
function transformArray(oldJson, newJson, unchanged, patches, patchHashes, path, jsondiff) {
//When is the Array, stop to find leaf node
// (hash, value, index)
var x = hashObject.mapArray(hashObject.hash, oldJson, HASH_ID);
var y = hashObject.mapArray(hashObject.hash, newJson, HASH_ID);
// Reserve the origin index
// COPY ARRAY
var x_sorted = x.slice();
var y_sorted = y.slice();
x_sorted.sort(function(a, b) {return a.hash - b.hash;});
y_sorted.sort(function(a, b) {return a.hash - b.hash;});
//Diff
var arrPatch = [], arrUnchanged = [], arrtmp = [];
var i= 0, j = 0;
while (i < x_sorted.length) {
while( j < y_sorted.length) {
if(x_sorted[i] !== void 0) {
if (x_sorted[i].hash > y_sorted[j].hash) {
arrPatch.push({op: "add", value: y_sorted[j].value, index: y_sorted[j].index, hash: y_sorted[j].hash });
j++;
} else if (x_sorted[i].hash === y_sorted[j].hash) {
// Unchanged push
unchanged.push( path + '/' + y_sorted[j].index + "=" + JSON.stringify(x_sorted[i].hash));
arrPatch.push({op: "move", value: y_sorted[j].value, valueOld: x_sorted[i].value, from: x_sorted[i].index , index: y_sorted[j].index, hash: y_sorted[j].hash });
i++;
j++;
} else {
arrPatch.push({op: "remove", index: x_sorted[i].index, value: x_sorted[i].value});
i++;
}
} else {
arrPatch.push({op: "add", value: y_sorted[j].value, index: y_sorted[j].index, hash: y_sorted[j].hash });
j++;
}
}
if (i < x_sorted.length) {
// Remove the rest elements of the x_sorted
arrPatch.push({op: "remove", index: x_sorted[i].index, value: x_sorted[i].value });
i++;
}
}
//Get the patch to make all the elements are the same, but index is random
arrPatch = arrPatch.sort(compare);
var m = 0;
while(arrPatch[m] !== void 0) {
// f_index = transformIndex(arrPatch[m], arrPatch);
switch(arrPatch[m].op) {
case 'add':
arrPatch[m].index = transformIndex(arrPatch[m], m, arrPatch);
// replace
if (arrPatch[m-1] !== void 0 ) {
if (arrPatch[m-1].op === 'remove' && arrPatch[m-1].index === arrPatch[m].index) {
// if replace a object, go deeper
// Set thresholds length == 30
// if (JSON.stringify(arrPatch[m-1].value).length > 20 && typeof arrPatch[m-1].value === "object" && arrPatch[m-1].value !== null && typeof arrPatch[m].value === "object" && arrPatch[m].value !== null) {
if (typeof arrPatch[m-1].value === "object" && arrPatch[m-1].value !== null && typeof arrPatch[m].value === "object" && arrPatch[m].value !== null) {
if (ARR_COM === true) {
var tmPatch = [];
//1.
generateDiff(arrPatch[m-1].value, arrPatch[m].value, unchanged, tmPatch, path + "/" + arrPatch[m-1].index);
//2.
// tmPatch = fjp.compare(arrPatch[m-1].value, arrPatch[m].value);
//Need to be fixed.
arrPatch[m].op = 'replace';
arrPatch.splice(m-1,1);
arrtmp.pop();
arrtmp = arrtmp.concat(tmPatch);
continue;
} else {
arrPatch[m].op = 'replace';
arrPatch.splice(m-1,1);
arrtmp.pop();
arrtmp.push({op: "replace", value: arrPatch[m-1].value, path: path + '/' + arrPatch[m-1].index});
continue;
}
} else {
arrPatch[m].op = 'replace';
arrPatch.splice(m-1,1);
arrtmp.pop();
arrtmp.push({op: "replace", value: arrPatch[m-1].value, path: path + '/' + arrPatch[m-1].index});
continue;
}
}
}
// COPY
var copyIndex = findCopyInArray(arrPatch[m], m, arrPatch, arrUnchanged);
if (copyIndex !== -1) {
arrPatch[m].op = 'copy';
arrPatch[m].from = copyIndex;
if (arrPatch[m].index === arrPatch[m].from) {
arrPatch.splice(m, 1);
continue;
}
arrtmp.push({op: "copy", from: path + '/' + arrPatch[m].from, path: path + '/' + arrPatch[m].index});
} else {
arrtmp.push({op: "add", value: arrPatch[m].value , path: path + '/' + arrPatch[m].index});
}
break;
case 'remove':
arrPatch[m].index = transformIndex(arrPatch[m], m, arrPatch);
if (arrPatch[m-1] !== void 0) {
// change move 2->1 and remove 2 to remove 1
if (arrPatch[m-1].op === 'move' && arrPatch[m-1].from === arrPatch[m].index && arrPatch[m-1].from === (arrPatch[m-1].index + 1) ) {
arrPatch[m].index = arrPatch[m-1].index;
arrPatch.splice(m-1,1);
arrtmp.pop();
arrtmp.push({op: "remove", path: path + '/' + arrPatch[m-1].index});
continue;
} else {
arrtmp.push({op: "remove", path: path + '/' + arrPatch[m].index});
}
} else {
arrtmp.push({op: "remove", path: path + '/' + arrPatch[m].index});
}
break;
case 'move':
arrPatch[m].from = transformIndex(arrPatch[m], m, arrPatch);
if (arrPatch[m].index === arrPatch[m].from) {
if (JSON.stringify(arrPatch[m].valueOld) === JSON.stringify(arrPatch[m].value)) {
arrUnchanged.push(arrPatch[m]);
arrPatch.splice(m, 1);
continue;
} else {
//If index is the same, go to the internal node
var tmMove = [];
generateDiff(arrPatch[m].valueOld, arrPatch[m].value, unchanged, tmMove, path + "/" + arrPatch[m].index);
// Remove current move in the patch.
arrPatch.splice(m,1);
arrtmp = arrtmp.concat(tmMove);
continue;
}
}
arrtmp.push({op: "move", from: path + '/' + arrPatch[m].from, path: path + '/' + arrPatch[m].index});
break;
}
m++;
}
arrPatch = arrPatch.map(function(obj) {
obj.path = path + '/' + obj.index;
delete obj.hash;
delete obj.index;
if (obj.op === 'move' || obj.op === 'copy') {
obj.from = path + '/' + obj.from;
delete obj.value;
}
return obj;
});
return arrtmp;
}