diff_xIndex method

int diff_xIndex(
  1. List<Diff> diffs,
  2. int loc
)

loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 diffs is a List of Diff objects. loc is the location within text1. Returns the location within text2.

Implementation

int diff_xIndex(List<Diff> diffs, int loc) {
  int chars1 = 0;
  int chars2 = 0;
  int last_chars1 = 0;
  int last_chars2 = 0;
  Diff? lastDiff;
  for (Diff aDiff in diffs) {
    if (aDiff.operation != Operation.insert) {
      // Equality or deletion.
      chars1 += aDiff.text.length;
    }
    if (aDiff.operation != Operation.delete) {
      // Equality or insertion.
      chars2 += aDiff.text.length;
    }
    if (chars1 > loc) {
      // Overshot the location.
      lastDiff = aDiff;
      break;
    }
    last_chars1 = chars1;
    last_chars2 = chars2;
  }
  if (lastDiff != null && lastDiff.operation == Operation.delete) {
    // The location was deleted.
    return last_chars2;
  }
  // Add the remaining character length.
  return last_chars2 + (loc - last_chars1);
}