getLevenshtein method

int? getLevenshtein(
  1. String b
)

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 b) {
  if (this.isBlank) {
    return null;
  }

  var a = this!.toLowerCase();
  b = b.toLowerCase();

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

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

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

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

  return costs[b.length];
}