closestName function

String? closestName(
  1. String wrong,
  2. Iterable<String> options
)

The closest of options to wrong (a typo of at most a third of the name), for a "did you mean" hint; null when none is close.

Implementation

String? closestName(String wrong, Iterable<String> options) {
  final target = ThemeValues.canonical(wrong);
  String? best;
  var bestDistance = 1 << 30;
  for (final option in options) {
    final distance = _distance(target, ThemeValues.canonical(option));
    if (distance < bestDistance) {
      bestDistance = distance;
      best = option;
    }
  }
  final limit = (target.length / 3).ceil().clamp(1, 3);
  return bestDistance <= limit ? best : null;
}