Skip to content

Commit

Permalink
refactor(ffe-formatters): optimize parser
Browse files Browse the repository at this point in the history
  • Loading branch information
pethel committed Nov 11, 2024
1 parent daa0ca2 commit 9a0e1d5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
5 changes: 3 additions & 2 deletions packages/ffe-formatters/src/formatNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 5 additions & 3 deletions packages/ffe-formatters/src/internal/parseNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

0 comments on commit 9a0e1d5

Please sign in to comment.