import type { Cents } from '../util/money';
export type Currency = { code: string; exponent: number };
export const currencies = {
USD: { code: 'USD', exponent: 2 },
EUR: { code: 'EUR', exponent: 2 },
GBP: { code: 'GBP', exponent: 2 },
JPY: { code: 'JPY', exponent: 0 },
KWD: { code: 'KWD', exponent: 3 },
} as const satisfies Record<string, Currency>;
export type CurrencyCode = keyof typeof currencies;
export function isCurrencyCode(code: string): code is CurrencyCode {
return code in currencies;
}
export function toMinorUnits(amount: number, code: CurrencyCode): Cents {
return Math.round(amount * 10 ** currencies[code].exponent);
}
export function formatMinorUnits(minor: Cents, code: CurrencyCode): string {
const { exponent } = currencies[code];
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: code,
minimumFractionDigits: exponent,
maximumFractionDigits: exponent,
}).format(minor / 10 ** exponent);
}