From 9a0e1d55d0e2ac5b70cd36db4ea91a92e148a2ea Mon Sep 17 00:00:00 2001 From: Peter Hellstrand Date: Mon, 11 Nov 2024 11:48:23 +0100 Subject: [PATCH] refactor(ffe-formatters): optimize parser --- packages/ffe-formatters/src/formatNumber.ts | 5 +++-- packages/ffe-formatters/src/internal/parseNumber.ts | 8 +++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/ffe-formatters/src/formatNumber.ts b/packages/ffe-formatters/src/formatNumber.ts index 0eebe51763..eecd7d149a 100644 --- a/packages/ffe-formatters/src/formatNumber.ts +++ b/packages/ffe-formatters/src/formatNumber.ts @@ -9,14 +9,15 @@ export const formatNumber = ( }, ) => { const { decimals = 0, locale } = opts; + const supportedLocale = locale === 'en' ? 'en' : 'nb'; - const toFormat = parseNumber(number, locale); + const toFormat = parseNumber(number, supportedLocale); if (typeof toFormat !== 'number') { return number; } - return new Intl.NumberFormat(locale === 'en' ? 'en' : 'nb', { + return new Intl.NumberFormat(supportedLocale, { maximumFractionDigits: decimals, minimumFractionDigits: decimals, }).format(toFormat); diff --git a/packages/ffe-formatters/src/internal/parseNumber.ts b/packages/ffe-formatters/src/internal/parseNumber.ts index 1cffc9dffe..165ac1de18 100644 --- a/packages/ffe-formatters/src/internal/parseNumber.ts +++ b/packages/ffe-formatters/src/internal/parseNumber.ts @@ -34,12 +34,14 @@ class NumberParser { } } +const nbParser = new NumberParser('nb'); +const enParser = new NumberParser('en'); + export const parseNumber = ( number: number | string | null | undefined, locale: Locale, ) => { - const parsed = new NumberParser(locale === 'en' ? 'en' : 'nb').parse( - `${number}`.replace(/\s/g, ''), - ); + const parser = locale === 'en' ? enParser : nbParser; + const parsed = parser.parse(`${number}`.replace(/\s/g, '')); return Number.isNaN(parsed) ? null : parsed; };