Skip to content

Latest commit

 

History

History
31 lines (21 loc) · 1.06 KB

File metadata and controls

31 lines (21 loc) · 1.06 KB

ArrayDiff

ArrayDiff computes the difference between two JavaScript arrays (as well as any other object that uses numeric subscripts, such as a string or DOMNodeList) by finding the longest common subsequence between them.

Example

var thisArray = 'nematode knowledge'.split(''),
    thatArray = 'empty bottle'.split(''),
    arrayDiff = new ArrayDiff(thatArray, thisArray);

arrayDiff.diff.forEach(function(element) {

    if (element.added()) {
        var operation = '+'
    } else if (element.removed()) {
        var operation = '-';
    } else {
        var operation = ' ';
    }
    
    console.log('%s %s', operation, element.item);
    
});

Acknowledgements

Many thanks to Professor David Eppstein of the University of California, Irvine, whose lecture notes from February 1996 helped me get my head around the dynamic programming solution to the longest common subsequence problem.