Skip to content

Commit

Permalink
fix: merge lines to diff overlapping content
Browse files Browse the repository at this point in the history
  • Loading branch information
KazariEX committed Oct 10, 2024
1 parent 00f7919 commit 66e37ba
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
28 changes: 13 additions & 15 deletions src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,34 +53,32 @@ function expand(chars: string[], start: number, end: number) {
return start - pos;
}

const inner = new Set(chars.slice(start, end));
const texts = chars.join("\n");
const startOffset = chars.slice(0, start).join("\n").length;
const endOffset = chars.slice(0, end).join("\n").length;

const left = [];
for (let i = start - 1, it = end - 1; inner.has(chars[i]); i--, it--) {
for (let i = start - 1, it = endOffset - 1; i < end && it >= startOffset; i--) {
const text = chars[i];

for (; it >= start; it--) {
if (chars[it] === text) {
break;
}
}
if (it >= start) {
const idx = texts.lastIndexOf(text, it);
if (idx !== -1 && idx >= startOffset) {
left.push(text);
it = idx - 1;
}
else break;
}

const right = [];
for (let i = end, it = start; inner.has(chars[i]); i++, it++) {
for (let i = end, it = startOffset; i >= start && it < endOffset; i++) {
const text = chars[i];

for (; it < end; it++) {
if (chars[it] === text) {
break;
}
}
if (it < end) {
const idx = texts.indexOf(text, it);
if (idx !== -1 && idx < endOffset) {
right.push(text);
it = idx + 1;
}
else break;
}

return [start - left.length, end + right.length] as const;
Expand Down
13 changes: 12 additions & 1 deletion test/diff.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { expect, it } from "vitest";
import { diff } from "../src/diff";
import type { LoadLine } from "../src/types";

it("add 1 line has different content with adjacent", () => {
expect(diffWith(
Expand Down Expand Up @@ -66,6 +65,18 @@ it("add N lines have discontinuous sequential subset in adjacent", () => {
["A", "B", "A", "C", "B", "D", "C", "D"]
// ^ ^ |^| ^ ^ |^| ^ ^
)).toEqual([0, 8]);

expect(diffWith(
["A", "B", "C"],
["A", "B", "CA", "B", "C"]
// ^ ^ |^^| ^ ^
)).toEqual([0, 5]);

expect(diffWith(
["A", "B", "C", "D"],
["A", "B", "CA", "DB", "C", "D"]
// ^ ^ |^^| |^^| ^ ^
)).toEqual([0, 6]);
});

function diffWith(oldChars: string[], newChars: string[]) {
Expand Down

0 comments on commit 66e37ba

Please sign in to comment.