mdiff
v1.4.2
Published
An LCS Implementaion for Arrays and Strings
Maintainers
Readme
mdiff
A Minimalistic Diff Implementation
Based on the algorithm proposed in "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). Works with Arrays and Strings.
Usage
$ npm install mdiffimport mdiff from 'mdiff';
let a = 'ABCABBA';
let b = 'CBABAC';
let diff = mdiff(a, b);
console.log("lcs='%s'", diff.getLcs());
console.log("Common:");
let d = diff.scanCommon((aS, aE, bS, bE) => {
console.log(" '%s' == '%s'", a.slice(aS, aE), b.slice(bS, bE));
});
console.log("edit-distance=%s", d);
console.log("Diff:");
d = diff.scanDiff((aS, aE, bS, bE) => {
console.log(" '%s' -> '%s'", a.slice(aS, aE), b.slice(bS, bE));
});
console.log("edit-distance=%s", d);API
var diff = mdiff(a, b, options)
Creates a diff-object.
a,b(strings or arrays): the items to be compared.optionsequal(function(aValue, bValue)): a comparator that determines if two entries are supposed to be equal (default is just===).indexEqual(function(aIdx, bIdx)): a comparator that determines if entries for two indices are supposed to be equal (default is to comparea[aIdx]withb[bIdx]byequal).
diff.scanCommon(cb, dMax)
Calls cb for each common slice and returns the edit-distance d.
cb(function(aS, aE, bS, bE)): reports the corresponding slices with these guarantees:- non-emptiness:
aE - aS == bE - bS > 0 - monotony:
aSis not less thanaEfrom the previous call.bSis not less thanbEfrom the previous call. - equality:
a.slice(aS, aE)is equalb.slice(bS, bE)with respect toequal. - minimality: The sum of all
aS - aEis equal to(a.length + b.length - d) / 2and there is no lesserdso that 'equality' holds.
- non-emptiness:
dMax(optional): the maximum edit-distance to be handled. If the items' edit-distance happens to exceed this value, the function never callscband returnsnull.
diff.scanDiff(cb, dMax)
Calls cb for each difference and returns the edit-distance d. This is just the complement of scanCommon.
cb(function(aS, aE, bS, bE)): reports differences with these guarantees:- non-emptiness:
aE - aS > 0orbE - bS > 0 - monotony:
aSis not less thanaEfrom the previous call.bSis not less thanbEfrom the previous call. - equality: If in
aall slicesa.slice(aS, aE)are replaced by their correspondingb.slice(bS, bE), the result is equal tobwith respect toequal. - minimality: The sum of all
aS - aEplus the sum of allbS - bEis equal todand there is no lesserdso that 'equality' holds.
- non-emptiness:
dMax(optional): the maximum edit-distance to be handled. If the items' edit-distance happens to exceed this value, the function never callscband returnsnull.
diff.getLcs(dMax)
Returns the longest common subsequence of a and b (as a's type) or null, if the items' edit-distance exceeds dMax.
