parseLocaleParts method

E parseLocaleParts({
  1. required String languageCode,
  2. String? scriptCode,
  3. String? countryCode,
})

Finds the locale type E which fits the locale parts the best. Fallbacks to base locale.

Implementation

E parseLocaleParts({
  required String languageCode,
  String? scriptCode,
  String? countryCode,
}) {
  // Score every supported locale and pick the best one.
  // Language > script > country > same structure.
  // On ties, the first locale wins.
  int score(E supported) {
    int result = 0;
    final languageMatch = supported.languageCode == languageCode;
    if (languageMatch) {
      result += 4;
    }
    if (languageMatch &&
        scriptCode != null &&
        supported.scriptCode == scriptCode) {
      // a script is only meaningful within the same language
      result += 3;
    }
    if (countryCode != null && supported.countryCode == countryCode) {
      result += 2;
    }
    if (supported.scriptCode == scriptCode &&
        supported.countryCode == countryCode) {
      // same structure, e.g. "en" is better than "en-US" for "en"
      result += 1;
    }
    return result;
  }

  final best = locales.reduce((a, b) => score(b) > score(a) ? b : a);

  // require at least a language or country match
  return score(best) >= 2 ? best : baseLocale;
}