getLevenshtein method

int getLevenshtein(
  1. String other, [
  2. bool caseSensitive = true
])

The Levenshtein distance between two words is the minimum number of single-character

edits (insertions, deletions or substitutions) required to change one word into the other.

Example

String foo1 = 'esentis';
int dist = foo.getLevenshtein('esentis2'); // 1

Implementation

int getLevenshtein(String other, [bool caseSensitive = true]) {
  if (isBlank) {
    return other.length;
  }

  if (other.isBlank) {
    return length;
  }

  if (!caseSensitive) {
    return toLowerCase().getLevenshtein(other.toLowerCase());
  }

  List<int> costs = List<int>.filled(other.length + 1, 0);

  for (var j = 0; j <= other.length; j++) {
    costs[j] = j;
  }

  for (var i = 1; i <= length; i++) {
    int nw = costs[0];
    costs[0] = i;

    for (var j = 1; j <= other.length; j++) {
      int cj = min(1 + min(costs[j], costs[j - 1]), this[i - 1] == other[j - 1] ? nw : nw + 1);
      nw = costs[j];
      costs[j] = cj;
    }
  }

  return costs[other.length];
}