Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(ffe-formatters): optimize parser #2414

Merged
merged 1 commit into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
};
Loading