matchScale static method

String matchScale({
  1. required List<String> files,
  2. int scale = 1,
  3. required String name,
  4. required String extension,
})

Implementation

static String matchScale({
  required List<String> files,
  int scale = 1,
  required String name,
  required String extension,
}) {
  files.sort();
  files = files.reversed.toList();

  final regex = RegExp(
    '$name(@(\\d+)x)?\\.$extension\$',
    unicode: true,
    caseSensitive: false,
  );

  int closestScale = 0;

  final matches = <String>[];
  for (final file in files) {
    final match = regex.firstMatch(file);
    if (match != null) {
      String? group = match[2];
      if (group == null) {
        if (scale == 1) return match.input;
        group = '1';
      }

      final matchedScale = int.parse(group);
      if (matchedScale == scale) return match.input;

      if (matchedScale < scale) {
        if (closestScale < matchedScale) closestScale = matchedScale;
      } else if (closestScale < matchedScale) {
        closestScale = matchedScale;
      }

      matches.add(match.input);
    }
  }
  final scaledMatches = matches
      .where(
        (element) => RegExp(
          '$name(@${closestScale}x)?\\.$extension\$',
          unicode: true,
          caseSensitive: false,
        ).hasMatch(element),
      )
      .toList();
  scaledMatches.sort();
  return scaledMatches.last;
}