Compute diff-array patch in JavaScript

I want to create an object that will be effectively used as a patch for array A to create array B.

For the isSame function, which compares two values ​​and returns true if they are the same, or false otherwise (and whose purpose is to compare two elements of the array), is there a known algorithm for calculating the difference between two arrays and return a list of specific differences? The differences consist of sets: X elements deleted with index Y, and the following elements inserted in index Y.

I wrote something like this, but at the moment it’s a buggy, and I am having problems progressing on it, and I’m worried that I am reinventing the wheel when someone else could do it, http://jsfiddle.net/ G6tYt / 1 /

+4
source share
1 answer

If you want the comparison to be both deep and tolerant of objects and arrays, then this tool, which I wrote some time ago, can be useful:

https://github.com/danski/spahql/blob/master/src/SpahQL.DataHelper.js#L18

 SpahQL.DataHelper.compare( {"a": "aval", "b": "bval", "c": "cval", "arr": [0,1,2]}, {"a": "modified", "c": "cval", "d": "added", "arr": [0,1,2,3]} ); // -> {"/": "~", "/a": "~", "/b": "-", "/d": "+", "/arr": "~", "/arr/3": "+"} 
+1
source

All Articles