From 079ddd0bba55d99a36a923d16e4ef86e9c64fa86 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 31 Dec 2023 12:23:26 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20buffer=20insertions=20to?= =?UTF-8?q?=20avoid=20greedy=20alternating=20of=20red=20/=20green=20in=20d?= =?UTF-8?q?iff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/diff/diffLines.ts | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/core/diff/diffLines.ts b/core/diff/diffLines.ts index f055b2b54..ab08e22e3 100644 --- a/core/diff/diffLines.ts +++ b/core/diff/diffLines.ts @@ -10,6 +10,10 @@ export async function* streamDiff( ): AsyncGenerator { oldLines = [...oldLines]; // be careful + // Greedy gives you alternating red/green + // Buffering to wait until end of block avoids this + let buffer: DiffLine[] = []; + let newLineResult = await newLines.next(); while (oldLines.length > 0 && !newLineResult.done) { const [matchIndex, isPerfectMatch, newLine] = matchLine( @@ -18,16 +22,33 @@ export async function* streamDiff( ); if (matchIndex < 0) { + // Empty buffer + while (buffer.length) { + yield buffer.shift()!; + } + + // Insert new line yield { type: "new", line: newLine }; } else { + if (isPerfectMatch) { + // Empty buffer + while (buffer.length) { + yield buffer.shift()!; + } + } + + // Insert all deleted lines before match for (let i = 0; i < matchIndex; i++) { yield { type: "old", line: oldLines.shift()! }; } + if (isPerfectMatch) { + // Same yield { type: "same", line: oldLines.shift()! }; } else { + // Delete old and buffer insertion of the new yield { type: "old", line: oldLines.shift()! }; - yield { type: "new", line: newLine }; + buffer.push({ type: "new", line: newLine }); } } @@ -39,7 +60,14 @@ export async function* streamDiff( for (let oldLine of oldLines) { yield { type: "old", line: oldLine }; } - } else if (!newLineResult.done && oldLines.length === 0) { + } + + // Empty the buffer - (important that this is between the above and below loops) + while (buffer.length) { + yield buffer.shift()!; + } + + if (!newLineResult.done && oldLines.length === 0) { yield { type: "new", line: newLineResult.value }; for await (const newLine of newLines) { yield { type: "new", line: newLine };