All files / packages/app/utils currency.ts

90% Statements 18/20
70% Branches 7/10
100% Functions 4/4
89.47% Lines 17/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                240x         18779x         240x       9587x       9587x 14843x 9587x       240x           240x       2207x 2207x         2207x     2207x 36x 36x       2171x     2207x    
import { capitalize } from "remeda";
 
import type { Locale } from "~app/utils/locale";
 
export type CurrencyCode = string & {
	__flavor?: "currencyCode";
};
 
export const formatCurrency = (
	locale: Locale,
	currencyCode: CurrencyCode,
	value: number,
) =>
	new Intl.NumberFormat(locale, {
		style: "currency",
		currency: currencyCode,
	}).format(value);
 
export const getCurrencySymbol = (
	locale: Locale,
	currencyCode: CurrencyCode,
) => {
	const formatter = new Intl.NumberFormat(locale, {
		style: "currency",
		currency: currencyCode,
	});
	const parts = formatter.formatToParts(0);
	const symbolPart = parts.find((part) => part.type === "currency");
	return symbolPart?.value ?? currencyCode;
};
 
// see https://issues.chromium.org/issues/566540087
const FALLBACK_CODES: Partial<Record<CurrencyCode, string>> = {
	SLE: "Sierra Leonean Leone (SLE)",
	XCG: "Caribbean guilder (Cg. / XCG)",
	ZWG: "Zimbabwean Gold (ZWG)",
};
 
export const getCurrencyDescription = (
	locale: Locale,
	currencyCode: CurrencyCode,
) => {
	const currencySymbol = getCurrencySymbol(locale, currencyCode);
	const displayName = new Intl.DisplayNames(locale, {
		type: "currency",
		fallback: "none",
	}).of(currencyCode);
	const symbol =
		currencySymbol === currencyCode
			? currencySymbol
			: `${currencySymbol} / ${currencyCode}`;
	if (!displayName) {
		Eif (FALLBACK_CODES[currencyCode]) {
			return FALLBACK_CODES[currencyCode];
		}
		return symbol;
	}
	Iif (displayName === symbol) {
		return displayName;
	}
	return `${capitalize(displayName)} (${symbol})`;
};