-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathjson-diff.html
More file actions
1052 lines (939 loc) · 27.6 KB
/
json-diff.html
File metadata and controls
1052 lines (939 loc) · 27.6 KB
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON Diff Tool</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: Helvetica, Arial, sans-serif;
margin: 0;
padding: 20px;
background: #f5f5f5;
min-height: 100vh;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 10px;
}
.examples {
text-align: center;
margin-bottom: 20px;
padding: 12px;
background: #e8f4fc;
border-radius: 8px;
}
.examples span {
color: #666;
margin-right: 10px;
}
.examples a {
color: #0066cc;
text-decoration: none;
margin: 0 8px;
cursor: pointer;
}
.examples a:hover {
text-decoration: underline;
}
.input-section {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 20px;
}
.input-panel {
display: flex;
flex-direction: column;
}
.input-panel label {
font-weight: bold;
margin-bottom: 8px;
color: #444;
}
.input-panel textarea {
width: 100%;
height: 250px;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 16px;
padding: 12px;
border: 2px solid #ddd;
border-radius: 8px;
resize: vertical;
background: #fff;
}
.input-panel textarea:focus {
outline: none;
border-color: #0066cc;
}
.left-panel textarea {
border-left: 4px solid #dc3545;
}
.right-panel textarea {
border-left: 4px solid #28a745;
}
.button-row {
display: flex;
justify-content: center;
gap: 12px;
margin-bottom: 20px;
}
button {
padding: 12px 28px;
font-size: 16px;
font-weight: bold;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background 0.2s;
}
.compare-btn {
background: #0066cc;
color: white;
}
.compare-btn:hover {
background: #0055aa;
}
.clear-btn {
background: #666;
color: white;
}
.clear-btn:hover {
background: #555;
}
.swap-btn {
background: #6c757d;
color: white;
}
.swap-btn:hover {
background: #5a6268;
}
.error {
background: #ffe6e6;
border: 1px solid #dc3545;
color: #dc3545;
padding: 12px;
border-radius: 6px;
margin-bottom: 20px;
text-align: center;
}
.result-section {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.result-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 1px solid #eee;
}
.result-header h2 {
margin: 0;
color: #333;
}
.legend {
display: flex;
gap: 20px;
font-size: 14px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-color {
width: 16px;
height: 16px;
border-radius: 3px;
}
.legend-added {
background: #d4edda;
border: 1px solid #28a745;
}
.legend-removed {
background: #f8d7da;
border: 1px solid #dc3545;
}
.legend-modified {
background: #fff3cd;
border: 1px solid #ffc107;
}
.diff-container {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 14px;
line-height: 1.6;
overflow-x: auto;
}
.diff-line {
padding: 4px 12px;
border-radius: 3px;
margin: 2px 0;
white-space: pre-wrap;
word-break: break-word;
}
.diff-added {
background: #d4edda;
border-left: 4px solid #28a745;
}
.diff-removed {
background: #f8d7da;
border-left: 4px solid #dc3545;
}
.diff-modified {
background: #fff3cd;
border-left: 4px solid #ffc107;
}
.diff-unchanged {
color: #666;
}
.diff-path {
color: #0066cc;
font-weight: bold;
}
.diff-value {
color: #333;
}
.diff-old-value {
color: #dc3545;
text-decoration: line-through;
}
.diff-new-value {
color: #28a745;
}
.diff-arrow {
color: #666;
margin: 0 8px;
}
.char-added {
background: #d4edda;
color: #155724;
}
.char-removed {
background: #f8d7da;
color: #721c24;
text-decoration: line-through;
}
.char-same {
color: #666;
}
.string-diff {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}
.summary {
display: flex;
gap: 20px;
margin-bottom: 16px;
padding: 12px;
background: #f8f9fa;
border-radius: 6px;
}
.summary-item {
font-size: 14px;
}
.summary-count {
font-weight: bold;
padding: 2px 8px;
border-radius: 12px;
margin-left: 4px;
}
.count-added {
background: #d4edda;
color: #155724;
}
.count-removed {
background: #f8d7da;
color: #721c24;
}
.count-modified {
background: #fff3cd;
color: #856404;
}
.no-diff {
text-align: center;
padding: 40px;
color: #28a745;
font-size: 18px;
}
.no-diff::before {
content: "✓ ";
}
@media (max-width: 768px) {
.input-section {
grid-template-columns: 1fr;
}
.legend {
flex-wrap: wrap;
gap: 10px;
}
.result-header {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
}
</style>
</head>
<body>
<div class="container">
<h1>JSON Diff Tool</h1>
<div class="examples">
<span>Try examples:</span>
<a onclick="loadExample('config')">Config changes</a>
<a onclick="loadExample('user')">User profile update</a>
<a onclick="loadExample('api')">API response versions</a>
<a onclick="loadExample('nested')">Nested structure</a>
<a onclick="loadExample('array')">Array modifications</a>
</div>
<div class="input-section">
<div class="input-panel left-panel">
<label for="json1">Original JSON (left)</label>
<textarea id="json1" placeholder="Paste your original JSON here..."></textarea>
</div>
<div class="input-panel right-panel">
<label for="json2">Modified JSON (right)</label>
<textarea id="json2" placeholder="Paste your modified JSON here..."></textarea>
</div>
</div>
<div class="button-row">
<button class="compare-btn" onclick="compare()">Compare</button>
<button class="swap-btn" onclick="swap()">⇄ Swap</button>
<button class="clear-btn" onclick="clearAll()">Clear</button>
</div>
<div id="error" class="error" style="display: none;"></div>
<div id="result" class="result-section" style="display: none;">
<div class="result-header">
<h2>Differences</h2>
<div class="legend">
<div class="legend-item">
<div class="legend-color legend-added"></div>
<span>Added</span>
</div>
<div class="legend-item">
<div class="legend-color legend-removed"></div>
<span>Removed</span>
</div>
<div class="legend-item">
<div class="legend-color legend-modified"></div>
<span>Modified</span>
</div>
</div>
</div>
<div id="summary" class="summary"></div>
<div id="diff" class="diff-container"></div>
</div>
</div>
<script type="module">
const examples = {
config: {
left: {
"appName": "MyApp",
"version": "1.2.0",
"debug": true,
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp_dev"
},
"features": {
"darkMode": false,
"notifications": true,
"analytics": false
},
"maxConnections": 10
},
right: {
"appName": "MyApp",
"version": "1.3.0",
"debug": false,
"database": {
"host": "db.production.com",
"port": 5432,
"name": "myapp_prod",
"ssl": true
},
"features": {
"darkMode": true,
"notifications": true,
"analytics": true,
"betaFeatures": false
},
"maxConnections": 100,
"cacheEnabled": true
}
},
user: {
left: {
"id": 12345,
"username": "johndoe",
"email": "john@example.com",
"profile": {
"firstName": "John",
"lastName": "Doe",
"age": 28,
"bio": "Software developer"
},
"preferences": {
"theme": "light",
"language": "en",
"timezone": "UTC"
},
"lastLogin": "2024-01-15T10:30:00Z"
},
right: {
"id": 12345,
"username": "johndoe",
"email": "john.doe@newcompany.com",
"profile": {
"firstName": "John",
"lastName": "Doe",
"age": 29,
"bio": "Senior software engineer at TechCorp",
"avatar": "https://example.com/avatar.jpg"
},
"preferences": {
"theme": "dark",
"language": "en",
"timezone": "America/New_York",
"notifications": true
},
"lastLogin": "2024-03-20T14:45:00Z"
}
},
api: {
left: {
"status": "success",
"data": {
"products": [
{"id": 1, "name": "Widget", "price": 9.99, "stock": 100},
{"id": 2, "name": "Gadget", "price": 19.99, "stock": 50}
],
"pagination": {
"page": 1,
"perPage": 10,
"total": 2
}
},
"meta": {
"apiVersion": "v1",
"timestamp": "2024-01-01T00:00:00Z"
}
},
right: {
"status": "success",
"data": {
"products": [
{"id": 1, "name": "Widget Pro", "price": 12.99, "stock": 75, "featured": true},
{"id": 2, "name": "Gadget", "price": 19.99, "stock": 50},
{"id": 3, "name": "Gizmo", "price": 29.99, "stock": 25}
],
"pagination": {
"page": 1,
"perPage": 10,
"total": 3,
"hasMore": false
}
},
"meta": {
"apiVersion": "v2",
"timestamp": "2024-06-01T00:00:00Z",
"deprecationWarning": null
}
}
},
nested: {
left: {
"company": {
"name": "TechStartup Inc",
"departments": {
"engineering": {
"headCount": 15,
"teams": {
"frontend": {"members": 5, "lead": "Alice"},
"backend": {"members": 6, "lead": "Bob"}
}
},
"marketing": {
"headCount": 8,
"budget": 50000
}
}
}
},
right: {
"company": {
"name": "TechStartup Inc",
"departments": {
"engineering": {
"headCount": 25,
"teams": {
"frontend": {"members": 8, "lead": "Alice", "remote": true},
"backend": {"members": 10, "lead": "Charlie"},
"devops": {"members": 4, "lead": "Diana"}
}
},
"marketing": {
"headCount": 12,
"budget": 75000
},
"sales": {
"headCount": 6,
"budget": 40000
}
}
}
}
},
array: {
left: {
"playlist": {
"name": "Road Trip Mix",
"songs": [
{"title": "Highway Star", "artist": "Deep Purple", "duration": 367},
{"title": "Born to Run", "artist": "Bruce Springsteen", "duration": 270},
{"title": "Life is a Highway", "artist": "Tom Cochrane", "duration": 261}
],
"totalDuration": 898,
"isPublic": false
}
},
right: {
"playlist": {
"name": "Ultimate Road Trip Mix",
"songs": [
{"title": "Highway Star", "artist": "Deep Purple", "duration": 367},
{"title": "Radar Love", "artist": "Golden Earring", "duration": 378},
{"title": "Born to Run", "artist": "Bruce Springsteen", "duration": 270},
{"title": "Take It Easy", "artist": "Eagles", "duration": 211}
],
"totalDuration": 1226,
"isPublic": true,
"followers": 42
}
}
}
};
function diffArrays(arr1, arr2, path) {
const diffs = [];
const maxLen = Math.max(arr1.length, arr2.length);
for (let i = 0; i < maxLen; i++) {
const currentPath = `${path}[${i}]`;
const val1 = arr1[i];
const val2 = arr2[i];
if (i >= arr1.length) {
// Element only in arr2 - added
diffs.push({type: 'added', path: currentPath, value: val2});
} else if (i >= arr2.length) {
// Element only in arr1 - removed
diffs.push({type: 'removed', path: currentPath, value: val1});
} else if (typeof val1 !== typeof val2) {
diffs.push({type: 'modified', path: currentPath, oldValue: val1, newValue: val2});
} else if (typeof val1 === 'object' && val1 !== null && !Array.isArray(val1)) {
// Both are objects - recursively diff
diffs.push(...deepDiff(val1, val2, currentPath));
} else if (Array.isArray(val1) && Array.isArray(val2)) {
// Both are arrays - recursively diff arrays
diffs.push(...diffArrays(val1, val2, currentPath));
} else if (val1 !== val2) {
diffs.push({type: 'modified', path: currentPath, oldValue: val1, newValue: val2});
}
// If val1 === val2, no diff needed (element unchanged)
}
return diffs;
}
function deepDiff(obj1, obj2, path = '') {
const diffs = [];
const allKeys = new Set([...Object.keys(obj1 || {}), ...Object.keys(obj2 || {})]);
for (const key of allKeys) {
const currentPath = path ? `${path}.${key}` : key;
const val1 = obj1?.[key];
const val2 = obj2?.[key];
if (!(key in (obj1 || {}))) {
diffs.push({type: 'added', path: currentPath, value: val2});
} else if (!(key in (obj2 || {}))) {
diffs.push({type: 'removed', path: currentPath, value: val1});
} else if (typeof val1 !== typeof val2) {
diffs.push({type: 'modified', path: currentPath, oldValue: val1, newValue: val2});
} else if (typeof val1 === 'object' && val1 !== null && !Array.isArray(val1)) {
diffs.push(...deepDiff(val1, val2, currentPath));
} else if (Array.isArray(val1) && Array.isArray(val2)) {
diffs.push(...diffArrays(val1, val2, currentPath));
} else if (val1 !== val2) {
diffs.push({type: 'modified', path: currentPath, oldValue: val1, newValue: val2});
}
}
return diffs;
}
function formatValue(value) {
if (typeof value === 'string') return `"${value}"`;
if (value === null) return 'null';
if (Array.isArray(value) || typeof value === 'object') {
return JSON.stringify(value, null, 2);
}
return String(value);
}
function escapeHtml(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function diffStrings(oldStr, newStr) {
// Compute LCS-based character diff
const m = oldStr.length;
const n = newStr.length;
// Build LCS table
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (oldStr[i - 1] === newStr[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// Backtrack to find diff operations
const ops = [];
let i = m, j = n;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && oldStr[i - 1] === newStr[j - 1]) {
ops.unshift({type: 'same', char: oldStr[i - 1]});
i--; j--;
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
ops.unshift({type: 'add', char: newStr[j - 1]});
j--;
} else {
ops.unshift({type: 'del', char: oldStr[i - 1]});
i--;
}
}
// Build HTML with grouped spans
let html = '"';
let currentType = null;
let buffer = '';
for (const op of ops) {
if (op.type !== currentType) {
if (buffer) {
if (currentType === 'same') html += `<span class="char-same">${escapeHtml(buffer)}</span>`;
else if (currentType === 'del') html += `<span class="char-removed">${escapeHtml(buffer)}</span>`;
else if (currentType === 'add') html += `<span class="char-added">${escapeHtml(buffer)}</span>`;
}
buffer = op.char;
currentType = op.type;
} else {
buffer += op.char;
}
}
if (buffer) {
if (currentType === 'same') html += `<span class="char-same">${escapeHtml(buffer)}</span>`;
else if (currentType === 'del') html += `<span class="char-removed">${escapeHtml(buffer)}</span>`;
else if (currentType === 'add') html += `<span class="char-added">${escapeHtml(buffer)}</span>`;
}
html += '"';
return html;
}
function renderDiff(diffs) {
if (diffs.length === 0) {
return '<div class="no-diff">The JSON documents are identical</div>';
}
return diffs.map(diff => {
const pathHtml = `<span class="diff-path">${diff.path}</span>`;
if (diff.type === 'added') {
return `<div class="diff-line diff-added">+ ${pathHtml}: <span class="diff-new-value">${formatValue(diff.value)}</span></div>`;
} else if (diff.type === 'removed') {
return `<div class="diff-line diff-removed">− ${pathHtml}: <span class="diff-old-value">${formatValue(diff.value)}</span></div>`;
} else {
// Check if both values are strings for character-level diff
if (typeof diff.oldValue === 'string' && typeof diff.newValue === 'string') {
const charDiff = diffStrings(diff.oldValue, diff.newValue);
return `<div class="diff-line diff-modified">± ${pathHtml}: <span class="string-diff">${charDiff}</span></div>`;
}
return `<div class="diff-line diff-modified">± ${pathHtml}: <span class="diff-old-value">${formatValue(diff.oldValue)}</span><span class="diff-arrow">→</span><span class="diff-new-value">${formatValue(diff.newValue)}</span></div>`;
}
}).join('');
}
function renderSummary(diffs) {
const added = diffs.filter(d => d.type === 'added').length;
const removed = diffs.filter(d => d.type === 'removed').length;
const modified = diffs.filter(d => d.type === 'modified').length;
return `
<div class="summary-item">Added: <span class="summary-count count-added">${added}</span></div>
<div class="summary-item">Removed: <span class="summary-count count-removed">${removed}</span></div>
<div class="summary-item">Modified: <span class="summary-count count-modified">${modified}</span></div>
`;
}
window.compare = function() {
const json1 = document.getElementById('json1').value.trim();
const json2 = document.getElementById('json2').value.trim();
const errorDiv = document.getElementById('error');
const resultDiv = document.getElementById('result');
errorDiv.style.display = 'none';
resultDiv.style.display = 'none';
if (!json1 || !json2) {
errorDiv.textContent = 'Please paste JSON in both fields';
errorDiv.style.display = 'block';
return;
}
let obj1, obj2;
try {
obj1 = JSON.parse(json1);
} catch (e) {
errorDiv.textContent = `Invalid JSON in left field: ${e.message}`;
errorDiv.style.display = 'block';
return;
}
try {
obj2 = JSON.parse(json2);
} catch (e) {
errorDiv.textContent = `Invalid JSON in right field: ${e.message}`;
errorDiv.style.display = 'block';
return;
}
const diffs = deepDiff(obj1, obj2);
document.getElementById('summary').innerHTML = renderSummary(diffs);
document.getElementById('diff').innerHTML = renderDiff(diffs);
resultDiv.style.display = 'block';
};
window.swap = function() {
const json1 = document.getElementById('json1');
const json2 = document.getElementById('json2');
const temp = json1.value;
json1.value = json2.value;
json2.value = temp;
};
window.clearAll = function() {
document.getElementById('json1').value = '';
document.getElementById('json2').value = '';
document.getElementById('error').style.display = 'none';
document.getElementById('result').style.display = 'none';
};
window.loadExample = function(name) {
const example = examples[name];
if (example) {
document.getElementById('json1').value = JSON.stringify(example.left, null, 2);
document.getElementById('json2').value = JSON.stringify(example.right, null, 2);
compare();
}
};
// TEST_SUITE_START
const testCases = [
{
name: "Array of objects - only last item changed",
left: {items: [{id: 1, name: "a"}, {id: 2, name: "b"}, {id: 3, name: "c"}]},
right: {items: [{id: 1, name: "a"}, {id: 2, name: "b"}, {id: 3, name: "changed"}]},
expectedDiffs: [{type: "modified", path: "items[2].name", oldValue: "c", newValue: "changed"}]
},
{
name: "Array of objects - all same except last item added",
left: {items: [{id: 1}, {id: 2}]},
right: {items: [{id: 1}, {id: 2}, {id: 3}]},
expectedDiffs: [{type: "added", path: "items[2]", value: {id: 3}}]
},
{
name: "Array of objects - last item removed",
left: {items: [{id: 1}, {id: 2}, {id: 3}]},
right: {items: [{id: 1}, {id: 2}]},
expectedDiffs: [{type: "removed", path: "items[2]", value: {id: 3}}]
},
{
name: "Nested array - only nested element changes",
left: {data: {arr: [1, 2, 3]}},
right: {data: {arr: [1, 2, 99]}},
expectedDiffs: [{type: "modified", path: "data.arr[2]", oldValue: 3, newValue: 99}]
},
{
name: "Multiple items unchanged, one in middle changed",
left: {list: ["a", "b", "c", "d"]},
right: {list: ["a", "X", "c", "d"]},
expectedDiffs: [{type: "modified", path: "list[1]", oldValue: "b", newValue: "X"}]
},
{
name: "Empty arrays are equal",
left: {arr: []},
right: {arr: []},
expectedDiffs: []
},
{
name: "Identical arrays have no diff",
left: {arr: [1, 2, 3]},
right: {arr: [1, 2, 3]},
expectedDiffs: []
},
{
name: "Array of complex objects - partial change",
left: {users: [{name: "Alice", age: 30}, {name: "Bob", age: 25}]},
right: {users: [{name: "Alice", age: 30}, {name: "Bob", age: 26}]},
expectedDiffs: [{type: "modified", path: "users[1].age", oldValue: 25, newValue: 26}]
},
{
name: "Deep nested array change",
left: {a: {b: {c: [{x: 1}, {x: 2}]}}},
right: {a: {b: {c: [{x: 1}, {x: 3}]}}},
expectedDiffs: [{type: "modified", path: "a.b.c[1].x", oldValue: 2, newValue: 3}]
},
{
name: "Array within array - element change",
left: {matrix: [[1, 2], [3, 4]]},
right: {matrix: [[1, 2], [3, 99]]},
expectedDiffs: [{type: "modified", path: "matrix[1][1]", oldValue: 4, newValue: 99}]
},
{
name: "Simple object property change",
left: {name: "old"},
right: {name: "new"},
expectedDiffs: [{type: "modified", path: "name", oldValue: "old", newValue: "new"}]
},
{
name: "Property added",
left: {a: 1},
right: {a: 1, b: 2},
expectedDiffs: [{type: "added", path: "b", value: 2}]
},
{
name: "Property removed",
left: {a: 1, b: 2},
right: {a: 1},
expectedDiffs: [{type: "removed", path: "b", value: 2}]
},
{
name: "Type change from number to string",
left: {val: 42},
right: {val: "42"},
expectedDiffs: [{type: "modified", path: "val", oldValue: 42, newValue: "42"}]
},
{
name: "Null to value",
left: {x: null},
right: {x: 5},
expectedDiffs: [{type: "modified", path: "x", oldValue: null, newValue: 5}]
},
{
name: "Array replaced by object",
left: {data: [1, 2]},
right: {data: {a: 1}},
expectedDiffs: [{type: "modified", path: "data", oldValue: [1, 2], newValue: {a: 1}}]
},
{
name: "Identical objects have no diff",
left: {a: 1, b: {c: 2}},
right: {a: 1, b: {c: 2}},
expectedDiffs: []
},
{
name: "Large array with single change at end",
left: {arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]},
right: {arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 100]},
expectedDiffs: [{type: "modified", path: "arr[9]", oldValue: 9, newValue: 100}]
},
{
name: "Object added to array element",
left: {items: [{id: 1}, {id: 2}]},
right: {items: [{id: 1}, {id: 2, extra: "new"}]},
expectedDiffs: [{type: "added", path: "items[1].extra", value: "new"}]
},
{
name: "Property removed from array element",
left: {items: [{id: 1, temp: true}, {id: 2}]},
right: {items: [{id: 1}, {id: 2}]},
expectedDiffs: [{type: "removed", path: "items[0].temp", value: true}]
},
{
name: "String with single character change",
left: {text: "hello world"},
right: {text: "hello World"},
expectedDiffs: [{type: "modified", path: "text", oldValue: "hello world", newValue: "hello World"}]
},
{
name: "String with prefix added",
left: {msg: "world"},
right: {msg: "hello world"},
expectedDiffs: [{type: "modified", path: "msg", oldValue: "world", newValue: "hello world"}]
},
{
name: "String with suffix removed",
left: {name: "John Doe Jr."},
right: {name: "John Doe"},
expectedDiffs: [{type: "modified", path: "name", oldValue: "John Doe Jr.", newValue: "John Doe"}]
},
{
name: "Complete string replacement",
left: {status: "pending"},
right: {status: "complete"},
expectedDiffs: [{type: "modified", path: "status", oldValue: "pending", newValue: "complete"}]
},
{
name: "Empty string to non-empty",
left: {value: ""},
right: {value: "filled"},
expectedDiffs: [{type: "modified", path: "value", oldValue: "", newValue: "filled"}]
}
];
function runTests() {
const results = [];
let passed = 0;
let failed = 0;
for (const test of testCases) {
const actualDiffs = deepDiff(test.left, test.right);
const actualStr = JSON.stringify(actualDiffs, null, 2);
const expectedStr = JSON.stringify(test.expectedDiffs, null, 2);
const success = actualStr === expectedStr;
if (success) {
passed++;
results.push({name: test.name, success: true});
} else {
failed++;
results.push({
name: test.name,
success: false,
expected: test.expectedDiffs,