Skip to content

Commit

Permalink
latest changes
Browse files Browse the repository at this point in the history
  • Loading branch information
morisil committed Jan 17, 2025
1 parent 9e82dd4 commit 30b591e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/commonMain/kotlin/compare/TextComparison.kt
Original file line number Diff line number Diff line change
Expand Up @@ -74,31 +74,52 @@ private fun diffLine(line1: String, line2: String): String {
var i = 0
var j = 0

// Buffers for grouping consecutive changes
val deletions = StringBuilder()
val additions = StringBuilder()

fun flushChanges() {
if (deletions.isNotEmpty()) {
builder.append("[-${deletions}-]")
deletions.clear()
}
if (additions.isNotEmpty()) {
builder.append("{+${additions}+}")
additions.clear()
}
}

while (i < line1.length || j < line2.length) {
when {
i >= line1.length -> {
builder.append("{+${line2[j]}+}")
// Only additions left
additions.append(line2[j])
j++
}
j >= line2.length -> {
builder.append("[-${line1[i]}-]")
// Only deletions left
deletions.append(line1[i])
i++
}
line1[i] == line2[j] -> {
// Characters match - flush any pending changes and append the matching character
flushChanges()
builder.append(line1[i])
i++
j++
}
else -> {
builder.append("[-${line1[i]}-]")
if (j < line2.length) {
builder.append("{+${line2[j]}+}")
}
// Characters differ - accumulate in respective buffers
deletions.append(line1[i])
additions.append(line2[j])
i++
j++
}
}
}

// Flush any remaining changes
flushChanges()

return builder.toString()
}
1 change: 1 addition & 0 deletions src/commonTest/kotlin/compare/TextComparisonTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ class TextComparisonTest {

private fun assertDifference(text1: String, text2: String, difference: String) {
val diff = text1 diff text2
assertEquals(difference, diff)
if ((diff != difference) && diff.isNotEmpty()) {
fail("The actual difference message was:\n${diff}")
}
Expand Down

0 comments on commit 30b591e

Please sign in to comment.