From 7fc3872146d4047b7200110dcd335eab2466cd02 Mon Sep 17 00:00:00 2001 From: Luca Silverentand Date: Wed, 18 Dec 2024 23:49:22 +0100 Subject: [PATCH] Refactor OuiLocale equality operator and hashCode implementation; enhance locale matching to be case insensitive --- oui/lib/src/utils/oui_localized.dart | 30 +++++++++------------- oui/test/src/utils/oui_localized_test.dart | 10 ++++++++ 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/oui/lib/src/utils/oui_localized.dart b/oui/lib/src/utils/oui_localized.dart index e266f3b..762b2a6 100644 --- a/oui/lib/src/utils/oui_localized.dart +++ b/oui/lib/src/utils/oui_localized.dart @@ -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. @@ -112,21 +102,25 @@ class OuiLocalized { } // 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; } diff --git a/oui/test/src/utils/oui_localized_test.dart b/oui/test/src/utils/oui_localized_test.dart index 8999d79..40e588e 100644 --- a/oui/test/src/utils/oui_localized_test.dart +++ b/oui/test/src/utils/oui_localized_test.dart @@ -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( + 'default', + { + OuiLocale('en', 'US'): 'Hello', + }, + ); + expect(localized.forLocale(const OuiLocale('EN', 'us')), 'Hello'); + }); }); }