fast-array-diff
Version:
Implementation of paper 'An O(ND) Difference Algorithm and Its Variations' on array
55 lines (54 loc) • 1.73 kB
JavaScript
import bestSubSequence from './lcs';
export function getPatch(a, b, compareFunc) {
if (compareFunc === void 0) { compareFunc = function (ia, ib) { return ia === ib; }; }
var patch = [];
var lastAdd = null;
var lastRemove = null;
function pushChange(type, oldArr, oldStart, oldEnd, newArr, newStart, newEnd) {
if (type === 'same') {
if (lastRemove) {
patch.push(lastRemove);
}
if (lastAdd) {
patch.push(lastAdd);
}
lastRemove = null;
lastAdd = null;
}
else if (type === 'remove') {
if (!lastRemove) {
lastRemove = {
type: 'remove',
oldPos: oldStart,
newPos: newStart,
items: [],
};
}
for (var i = oldStart; i < oldEnd; ++i) {
lastRemove.items.push(oldArr[i]);
}
if (lastAdd) {
lastAdd.oldPos += oldEnd - oldStart;
if (lastRemove.oldPos === oldStart) {
lastRemove.newPos -= oldEnd - oldStart;
}
}
}
else if (type === 'add') {
if (!lastAdd) {
lastAdd = {
type: 'add',
oldPos: oldStart,
newPos: newStart,
items: [],
};
}
for (var i = newStart; i < newEnd; ++i) {
lastAdd.items.push(newArr[i]);
}
}
}
bestSubSequence(a, b, compareFunc, pushChange);
pushChange('same', [], 0, 0, [], 0, 0);
return patch;
}