Created
August 14, 2014 13:31
-
-
Save posva/70482b1f30add86e424b to your computer and use it in GitHub Desktop.
Advanced diff between arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var diff = function(a, b) { | |
var c = [], dels = [], delsIndex = []; | |
var i = 0, j = 0, k, | |
x, y, z; | |
var t = 0; //debug | |
while (i < a.length || j < b.length) { | |
x = a[i]; | |
y = b[j]; | |
t++; | |
if (x === y) { // = | |
c.push({ | |
diff: "=", | |
val: x | |
}); | |
i++; | |
j++; | |
} else { // +, - or ~ | |
k = dels.indexOf(y); | |
if (k >= 0) { // ~ | |
z = dels.splice(k, 1)[0]; | |
delsIndex.shift(); | |
c.push({ | |
diff: "~", | |
val: z | |
}); | |
j++; | |
} else { | |
if (x === undefined || a.indexOf(y) < 0) { | |
c.push({ | |
diff: "+", | |
val: y | |
}); | |
j++; | |
} else { | |
dels.push(x); | |
delsIndex.push(c.length + dels.length - 1); | |
i++; | |
} | |
} | |
} | |
if (t > a.length + b.length) { | |
console.log("diff failed"); | |
break; | |
} | |
} | |
while (dels.length > 0) { | |
c.splice(delsIndex.shift(), 0, { | |
diff: "-", | |
val: dels.shift() | |
}); | |
} | |
return c; | |
}; | |
var c = diff([ 10, 1, 4, 3, 2, 7, 5, 8, 1, 2, 4], [1, 3, 4, 10, 2, 0, 6, 1, 4]), cc = []; | |
$.each(c, function(i, v) { | |
cc.push(v.diff+v.val); | |
}); | |
console.log(cc); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment