closestMatches function

List<String> closestMatches(
  1. String input,
  2. Iterable<String> candidates
)

Candidats proches de input, du plus au moins ressemblant (mêmes critères que closestMatch).

Implementation

List<String> closestMatches(String input, Iterable<String> candidates) {
  if (input.isEmpty) return const [];
  final scored = <(int, String)>[];
  for (final candidate in candidates) {
    if (candidate == input || candidate.isEmpty) continue;
    final d = _levenshtein(input, candidate);
    if (d > 2 || d >= input.length) continue;
    scored.add((d * 2 + (candidate[0] == input[0] ? 0 : 1), candidate));
  }
  // Tri stable : à score égal, l'ordre des candidats est conservé.
  final indexed = [for (var i = 0; i < scored.length; i++) (scored[i], i)];
  indexed.sort((a, b) {
    final byScore = a.$1.$1.compareTo(b.$1.$1);
    return byScore != 0 ? byScore : a.$2.compareTo(b.$2);
  });
  return [for (final entry in indexed) entry.$1.$2];
}