Skip to content

Commit

Permalink
Refactor OuiLocale equality operator and hashCode implementation; enh…
Browse files Browse the repository at this point in the history
…ance locale matching to be case insensitive
  • Loading branch information
lucasilverentand committed Dec 18, 2024
1 parent 95bb295 commit 7fc3872
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
30 changes: 12 additions & 18 deletions oui/lib/src/utils/oui_localized.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,6 @@ class OuiLocale {
/// The optional country code for localization, typically a two-letter code (e.g., 'US' for United States).
final String? countryCode;

@override
bool operator ==(Object other) =>
identical(this, other) ||
other is OuiLocale &&
other.languageCode == languageCode &&
other.countryCode == countryCode;

@override
int get hashCode => Object.hash(languageCode, countryCode);

/// Creates an instance of `OuiLocale` with the given language code and an optional country code.
///
/// The `languageCode` parameter is required and should be a valid ISO 639-1 language code.
Expand Down Expand Up @@ -112,21 +102,25 @@ class OuiLocalized<T> {
}

// Try exact match first (language + country)
if (_values.containsKey(locale)) {
return _values[locale]!;
final exactMatch = _values.keys.firstWhereOrNull(
(key) =>
key.languageCode.toLowerCase() == locale.languageCode.toLowerCase() &&
(key.countryCode?.toLowerCase() ?? '') ==
(locale.countryCode?.toLowerCase() ?? ''),
);
if (exactMatch != null) {
return _values[exactMatch]!;
}

// Try language-only match
final languageMatch = _values.keys
.firstWhereOrNull((key) => key.languageCode == locale.languageCode);
final languageMatch = _values.keys.firstWhereOrNull(
(key) =>
key.languageCode.toLowerCase() == locale.languageCode.toLowerCase(),
);
if (languageMatch != null) {
return _values[languageMatch]!;
}

if (_values.containsKey(languageMatch)) {
return _values[languageMatch]!;
}

// Fall back to default value
return _defaultValue;
}
Expand Down
10 changes: 10 additions & 0 deletions oui/test/src/utils/oui_localized_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,15 @@ void main() {
expect(localized.forLocale(const OuiLocale('en', 'US')), 'always');
expect(localized.forLocale(const OuiLocale('fr', 'FR')), 'always');
});

test('should be case insensitive for language/country codes', () {
const localized = OuiLocalized<String>(
'default',
{
OuiLocale('en', 'US'): 'Hello',
},
);
expect(localized.forLocale(const OuiLocale('EN', 'us')), 'Hello');
});
});
}

0 comments on commit 7fc3872

Please sign in to comment.