Files
web_app/src/core/DiffEngine.js
2026-02-23 09:08:15 +03:00

49 lines
1.4 KiB
JavaScript

export class DiffEngine {
build(oldText, newText) {
const a = (oldText ?? "").replace(/\r\n/g, "\n").split("\n");
const b = (newText ?? "").replace(/\r\n/g, "\n").split("\n");
const lcs = this.#lcsTable(a, b);
const ops = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i] === b[j]) {
ops.push({ kind: "equal", oldLine: a[i], newLine: b[j], oldIndex: i, newIndex: j });
i += 1;
j += 1;
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
ops.push({ kind: "remove", oldLine: a[i], oldIndex: i, newIndex: j });
i += 1;
} else {
ops.push({ kind: "add", newLine: b[j], oldIndex: i, newIndex: j });
j += 1;
}
}
while (i < a.length) {
ops.push({ kind: "remove", oldLine: a[i], oldIndex: i, newIndex: j });
i += 1;
}
while (j < b.length) {
ops.push({ kind: "add", newLine: b[j], oldIndex: i, newIndex: j });
j += 1;
}
return ops.map((op, index) => ({ ...op, id: index }));
}
#lcsTable(a, b) {
const rows = a.length + 1;
const cols = b.length + 1;
const table = Array.from({ length: rows }, () => Array(cols).fill(0));
for (let i = rows - 2; i >= 0; i -= 1) {
for (let j = cols - 2; j >= 0; j -= 1) {
if (a[i] === b[j]) table[i][j] = table[i + 1][j + 1] + 1;
else table[i][j] = Math.max(table[i + 1][j], table[i][j + 1]);
}
}
return table;
}
}