Diff Checker: how it works and how to build one
Compare two texts or files and highlight the changes. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Paste or open two versions of a text, config file or code and see added and removed lines side by side, with a count of changes. Option to ignore whitespace.
When to use it
- Comparing two versions of a document
- Checking config changes
- Reviewing copied code
How to use it
- Put the original on the left and the changed version on the right, or open files.
- Click Compare.
- Added lines are marked +, removed lines -.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/diff-checker
How it works
A diff finds the smallest set of lines to add and remove to turn one text into another. The classic method is the longest common subsequence (LCS): lines in the LCS are unchanged, everything else is added or removed.
The tool builds an LCS table with dynamic programming, then walks it backwards to list the changes.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
diff.ts (ts)
export function diffLines(a: string[], b: string[]) {
const m = a.length, n = b.length;
const L = Array.from({ length: m + 1 }, () => new Uint32Array(n + 1));
for (let i = m - 1; i >= 0; i--)
for (let j = n - 1; j >= 0; j--)
L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
const out: { t: " " | "+" | "-"; s: string }[] = [];
let i = 0, j = 0;
while (i < m && j < n) {
if (a[i] === b[j]) { out.push({ t: " ", s: a[i] }); i++; j++; }
else if (L[i + 1][j] >= L[i][j + 1]) out.push({ t: "-", s: a[i++] });
else out.push({ t: "+", s: b[j++] });
}
while (i < m) out.push({ t: "-", s: a[i++] });
while (j < n) out.push({ t: "+", s: b[j++] });
return out;
}
Make it production-ready
- Trim equal lines at the start and end first to save memory.
- Highlight changed words inside changed lines.
Questions
Is it a line diff or a word diff?
Line diff, like git diff. Changed lines appear as one removed and one added line.
Free, runs in your browser, nothing is uploaded.