resolveLocalizedUnitSymbol function
Resolve a localized token (possibly a full word or synonym) back to a canonical unit symbol.
This is used by parseLocalized helpers. Returns null if no mapping is found.
Resolves a localized token (full word or synonym) back to a canonical
unit symbol. Returns null if no mapping is found.
Implementation
String? resolveLocalizedUnitSymbol(String token, {String? locale}) {
if (token.isEmpty) return null;
final t = token.toLowerCase();
// 1) Custom synonyms take precedence
if (locale != null && locale.isNotEmpty) {
final key = locale.toLowerCase();
final syn = _customLocalizedSynonyms[key];
if (syn != null && syn.containsKey(t)) return syn[t];
}
// 2) Try to reverse-lookup default + custom localized names for the locale
String? tryReverse(String loc) {
final custom = _customLocalizedUnits[loc];
if (custom != null) {
for (final e in custom.entries) {
if (e.value.toLowerCase() == t) return e.key;
}
}
if (_defaultsEnabled) {
final defaults = _defaultLocalizedUnits[loc];
if (defaults != null) {
for (final e in defaults.entries) {
if (e.value.toLowerCase() == t) return e.key;
}
}
}
return null;
}
if (locale != null && locale.isNotEmpty) {
final normalized = locale.toLowerCase();
final exact = tryReverse(normalized);
if (exact != null) return exact;
final separatorIndex = normalized.indexOf(RegExp('[-_]'));
if (separatorIndex != -1) {
final base = normalized.substring(0, separatorIndex);
final baseMatch = tryReverse(base);
if (baseMatch != null) return baseMatch;
}
}
// 3) Fallback to English reverse lookup
final en = tryReverse('en');
if (en != null) return en;
// 4) Also accept raw symbols in any case
const allSymbols = [
'QB',
'RB',
'YB',
'ZB',
'EB',
'PB',
'TB',
'GB',
'MB',
'KB',
'B',
'YiB',
'ZiB',
'EiB',
'PiB',
'TiB',
'GiB',
'MiB',
'KiB',
'qb',
'rb',
'yb',
'zb',
'eb',
'pb',
'tb',
'gb',
'mb',
'kb',
'b',
'yib',
'zib',
'eib',
'pib',
'tib',
'gib',
'mib',
'kib',
];
final match = allSymbols.firstWhere(
(s) => s.toLowerCase() == t,
orElse: () => '',
);
return match.isEmpty ? null : match;
}