dvTypoMatches function

bool dvTypoMatches(
  1. String term,
  2. String candidate, {
  3. bool enabled = true,
})

Whether candidate is term allowing for a typo.

The budget scales with length rather than being flat, because a flat distance of two makes "ada" match "eve" -- an unrelated word of the same length, returned with full confidence. Under five characters nothing is tolerated; up to eight, one edit; beyond that, two.

A transposition of adjacent characters costs one edit rather than two: it is the most common typo there is, and counting it as two puts "recieve" outside the budget of the word it obviously means.

Implementation

bool dvTypoMatches(
  String term,
  String candidate, {
  bool enabled = true,
}) {
  final String a = term.toLowerCase();
  final String b = candidate.toLowerCase();
  if (a == b) return true;
  if (!enabled) return false;

  final int budget = a.length < 5 ? 0 : (a.length <= 8 ? 1 : 2);
  if (budget == 0) return false;
  // A length gap wider than the budget cannot be closed; skipping the matrix
  // here also keeps a long candidate from being compared against a short term.
  if ((a.length - b.length).abs() > budget) return false;

  return _damerauLevenshtein(a, b, budget) <= budget;
}