benjamine / jsondiffpatch

Diff & patch JavaScript objects
MIT License
4.78k stars 466 forks source link

incorrect array diff #294

Closed fricci closed 4 years ago

fricci commented 4 years ago

there is two array with a simple move difference between them:

{ "b": [1, 2, 10, 11, 12, 3, 20, 5] }

{ "b": [1, 2, 10, 11, 12, 5, 20, 3] }

As you see, the index 5 and index 7 swapped.

But the difference on the live page:

{ "b": { "_t": "a", "_6": [ "", 6, 3 ], "_7": [ "", 5, 3 ] }

which is incorrect I think (the element on index 6 wasn't moved)

about-code commented 4 years ago

I think it works as intended and what you are looking for has been documented here:

Note: in some cases, originalIndex and destinationIndex could be the same number, this might look weird, but remember the first refers to the original state (that's what the underscore means), and the later to the final state. When patching items are first all removed, and finally all inserted, so the composition of the array might be have changed in the middle.

So the misunderstanding may result from expecting the array's "delta" to be an actual delta or diff whereas in fact it's a list of move operations to be carried out on original or "left" to match destination or "right". What above note hints at is some implementation producing (simpliified) intermediate results as follows:

original:

[1, 2, 10, 11, 12, 3, 20, 5]

1. filtering/removing elements at index _6 and _7 yields

[1, 2, 10, 11, 12, 3]

2. moving value at original index _7 to target index 5 yields

{ "b": [1, 2, 10, 11, 12, 5, 3] }

3. moving value at original index _6 to target index 6 yields

{ "b": [1, 2, 10, 11, 12, 5, 20, 3] }
fricci commented 4 years ago

I overlooked this information in the documentation, sorry.

Thank you your detailed help, I'm closing the bug.