diff --git a/src/app/utils/formatCompactNumber.test.ts b/src/app/utils/formatCompactNumber.test.ts index f75661949..abc1b4e34 100644 --- a/src/app/utils/formatCompactNumber.test.ts +++ b/src/app/utils/formatCompactNumber.test.ts @@ -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', diff --git a/src/app/utils/formatCompactNumber.ts b/src/app/utils/formatCompactNumber.ts index a49da506b..b748ba1d6 100644 --- a/src/app/utils/formatCompactNumber.ts +++ b/src/app/utils/formatCompactNumber.ts @@ -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);