disambiguateName function

String disambiguateName(
  1. String name,
  2. Set<String> usedNames,
  3. Iterable<String> suffixes, {
  4. List<String> generateVariants(
    1. String candidate

Returns a name that is not contained in usedNames by suffixing it with the first possible suffix from suffixes.

The chosen name is added to usedNames.

If generateVariants is given, all the variants of a name must be available before that name is chosen, and all the chosen variants will be added to usedNames. The returned name is that, which will generate the accepted variants.


String disambiguateName(
    String name, Set<String> usedNames, Iterable<String> suffixes,
    {List<String> Function(String candidate)? generateVariants}) {
  generateVariants ??= (String name) => <String>[name];

  bool allVariantsAvailable(List<String> variants) {
    return variants.every((String variant) => !usedNames.contains(variant));

  var usedSuffix = '';
  var candidateVariants = generateVariants(name);

  if (!allVariantsAvailable(candidateVariants)) {
    for (final suffix in suffixes) {
      candidateVariants = generateVariants('$name$suffix');
      if (allVariantsAvailable(candidateVariants)) {
        usedSuffix = suffix;

  return '$name$usedSuffix';