untested fix for #854 fallback for unset system locale

This commit is contained in:
7w1 committed 2026-06-16 18:40:11 -05:00
1 parent 6c63cf9dcf
commit e46518f86a
2 files changed
+44 -2

No files matched your search

+21
View File
@@ -60,6 +60,27 @@ describe('formatCompactNumber', () => {
expect(format).toHaveBeenCalledWith(1_250_000);
});
it('filters invalid locale tags like c and falls back to en', () => {
const format = vi.fn<(num: number) => string>().mockReturnValue('formatted');
const numberFormat = vi
.spyOn(Intl, 'NumberFormat')
.mockImplementation(function MockNumberFormat(locales: Intl.LocalesArgument) {
const list = Array.isArray(locales) ? locales : [locales];
if (list.some((locale) => locale === 'c')) {
throw new RangeError('Invalid language tag: c');
}
return {
format,
} as unknown as Intl.NumberFormat;
} as typeof Intl.NumberFormat);
expect(formatCompactNumber(1_500, { locales: ['c', 'en'] })).toBe('formatted');
expect(numberFormat).toHaveBeenCalledWith(['en'], {
notation: 'compact',
maximumFractionDigits: 1,
});
});
it('uses Intl compact notation for formatted output', () => {
const expected = new Intl.NumberFormat(['fr-FR'], {
notation: 'compact',
+23 -2
View File
@@ -4,9 +4,30 @@ type FormatCompactNumberOptions = {
};
const DEFAULT_MAXIMUM_FRACTION_DIGITS = 1;
const FALLBACK_LOCALES: Intl.LocalesArgument = ['en'];
const isValidLocale = (locale: string): boolean => {
try {
Intl.NumberFormat(locale);
return true;
} catch {
return false;
}
};
const sanitizeLocales = (locales: Intl.LocalesArgument | undefined): Intl.LocalesArgument => {
if (locales === undefined) return FALLBACK_LOCALES;
const list = Array.isArray(locales) ? locales : [locales];
const valid = list.filter(
(locale): locale is string => typeof locale === 'string' && isValidLocale(locale)
);
return valid.length > 0 ? valid : FALLBACK_LOCALES;
};
const getDefaultLocales = (): Intl.LocalesArgument | undefined =>
typeof navigator === 'undefined' ? undefined : navigator.languages;
typeof navigator === 'undefined' ? undefined : sanitizeLocales(navigator.languages);
export function formatCompactNumber(
value: number,
@@ -15,7 +36,7 @@ export function formatCompactNumber(
maximumFractionDigits = DEFAULT_MAXIMUM_FRACTION_DIGITS,
}: FormatCompactNumberOptions = {}
): string {
return new Intl.NumberFormat(locales, {
return new Intl.NumberFormat(sanitizeLocales(locales), {
notation: 'compact',
maximumFractionDigits,
}).format(value);