|
| 1 | +import BigNumber from 'bignumber.js'; |
| 2 | +import memoize from 'memoize-one'; |
| 3 | +import type { CurrencyConfig } from 'src/modules/currency/currencies'; |
| 4 | +import { CURRENCIES, resolveOptions } from 'src/modules/currency/currencies'; |
| 5 | +import { minus as typographicMinus } from 'src/ui/shared/typography'; |
| 6 | + |
| 7 | +const getCurrencyFormatter = memoize((locale, currency, config = {}) => { |
| 8 | + return new Intl.NumberFormat(locale, { |
| 9 | + style: 'currency', |
| 10 | + currency, |
| 11 | + ...config, |
| 12 | + }); |
| 13 | +}); |
| 14 | + |
| 15 | +const getSmallPriceCurrencyFormatter = memoize( |
| 16 | + (locale, currency, config = {}) => { |
| 17 | + return new Intl.NumberFormat(locale, { |
| 18 | + style: 'currency', |
| 19 | + currency, |
| 20 | + minimumFractionDigits: 2, |
| 21 | + maximumSignificantDigits: 3, |
| 22 | + maximumFractionDigits: 20, |
| 23 | + ...config, |
| 24 | + }); |
| 25 | + } |
| 26 | +); |
| 27 | + |
| 28 | +// ~1$ values should be formatted as regular currency values |
| 29 | +const SMALL_VALUE_THRESHOLD = 0.99; |
| 30 | + |
| 31 | +export function formatPriceValue( |
| 32 | + value: BigNumber.Value, |
| 33 | + locale: string, |
| 34 | + currency: string, |
| 35 | + opts: Intl.NumberFormatOptions | null = null |
| 36 | +) { |
| 37 | + const number = value instanceof BigNumber ? value.toNumber() : Number(value); |
| 38 | + const sign = number < 0 ? typographicMinus : ''; |
| 39 | + const absValue = Math.abs(number); |
| 40 | + const isSmallValue = absValue < SMALL_VALUE_THRESHOLD; |
| 41 | + |
| 42 | + const config = CURRENCIES[currency] as CurrencyConfig | undefined; |
| 43 | + const numberFormatOptions = resolveOptions(number, config || null, opts); |
| 44 | + const formatter = isSmallValue |
| 45 | + ? getSmallPriceCurrencyFormatter(locale, currency, numberFormatOptions) |
| 46 | + : getCurrencyFormatter(locale, currency, numberFormatOptions); |
| 47 | + |
| 48 | + const modifyParts = config?.modifyParts; |
| 49 | + if (modifyParts) { |
| 50 | + const parts = formatter.formatToParts(absValue); |
| 51 | + return `${sign}${modifyParts(parts) |
| 52 | + .map((part) => part.value) |
| 53 | + .join('')}`; |
| 54 | + } |
| 55 | + return `${sign}${formatter.format(absValue)}`; |
| 56 | +} |
0 commit comments