This is an implementation of the patience diff algorithm in TypeScript. It compares two arrays of text lines and produces a diff result showing the differences.
- Finds inserted, deleted, and matched lines between two arrays of text
- Recursively finds the longest common subsequence (LCS) between slices of the input arrays
- Handles interleaved changes by recursively finding LCS matches within unmatched regions
patienceDifffunction provides basic diff with inserts, deletes and matchespatienceDiffPlusenhances it to also detect moved blocks of lines
Import the functions from the patienceDiff.ts file:
import { patienceDiff, patienceDiffPlus } from './patienceDiff';
Call patienceDiff to get a basic diff:
const diff = patienceDiff(originalLines, newLines);
Call patienceDiffPlus to also detect moved blocks:
const diff = patienceDiffPlus(originalLines, newLines);
The diff result object contains:
linesarray - the aligned lines from the input arrayslineCountDeleted- count of deleted lineslineCountInserted- count of inserted lineslineCountMoved- count of moved lines (only frompatienceDiffPlus)- Indices mapping moved lines (only from
patienceDiffPlus)
The patience diff algorithm works as follows:
- Find the longest common subsequence (LCS) between the two input arrays
- Recursively diff any lines before/after LCS matches
- Repeat process on unmatched regions to find all LCS matches
- Lines not part of any LCS are considered inserts or deletes
The patienceDiffPlus enhancement further analyzes lines not part of the LCS to detect moved blocks.
This implementation is based on the prior art of Jon Trent and the paper "An O(ND) Difference Algorithm and its Variations" by Eugene W. Myers