diff static method
Automatically calculates an edit from the differences between two strings. Finds the longest common prefix and suffix; the middle portion is the edit region.
Implementation
static TextEdit diff(String oldText, String newText) {
if (oldText == newText) return const TextEdit(0, 0, 0);
if (oldText.isEmpty) return TextEdit(0, 0, newText.length);
if (newText.isEmpty) return TextEdit(0, oldText.length, 0);
// Find the common prefix length
int prefixLen = 0;
final minLen = math.min(oldText.length, newText.length);
while (prefixLen < minLen && oldText[prefixLen] == newText[prefixLen]) {
prefixLen++;
}
// Find the common suffix length (without overlapping the prefix)
int suffixLen = 0;
final maxSuffix = minLen - prefixLen;
while (suffixLen < maxSuffix &&
oldText[oldText.length - 1 - suffixLen] ==
newText[newText.length - 1 - suffixLen]) {
suffixLen++;
}
return TextEdit(
prefixLen,
oldText.length - suffixLen,
newText.length - suffixLen,
);
}