2019-10-30 14:34:24 +00:00
|
|
|
import { IMoney } from "./Money";
|
2019-06-19 14:40:52 +00:00
|
|
|
|
|
|
|
export { default } from "./Money";
|
|
|
|
export * from "./Money";
|
|
|
|
|
2019-10-30 14:34:24 +00:00
|
|
|
export function addMoney(init: IMoney, ...args: IMoney[]): IMoney {
|
2019-06-19 14:40:52 +00:00
|
|
|
return {
|
|
|
|
amount: args.reduce((acc, curr) => acc + curr.amount, init.amount),
|
2022-06-21 09:36:55 +00:00
|
|
|
currency: init.currency,
|
2019-06-19 14:40:52 +00:00
|
|
|
};
|
|
|
|
}
|
2019-10-30 14:34:24 +00:00
|
|
|
export function subtractMoney(init: IMoney, ...args: IMoney[]): IMoney {
|
2019-06-19 14:40:52 +00:00
|
|
|
return {
|
|
|
|
amount: args.reduce((acc, curr) => acc - curr.amount, init.amount),
|
2022-06-21 09:36:55 +00:00
|
|
|
currency: init.currency,
|
2019-06-19 14:40:52 +00:00
|
|
|
};
|
|
|
|
}
|
2021-08-16 13:44:00 +00:00
|
|
|
|
|
|
|
export const formatMoney = (money: IMoney, locale: string) => {
|
|
|
|
try {
|
2022-11-02 11:20:25 +00:00
|
|
|
const formattedMoney = Intl.NumberFormat(locale, {
|
2022-06-21 09:36:55 +00:00
|
|
|
style: "currency",
|
2022-11-02 11:20:25 +00:00
|
|
|
currency: money.currency,
|
|
|
|
}).format(money.amount);
|
2021-08-16 13:44:00 +00:00
|
|
|
return formattedMoney;
|
|
|
|
} catch (error) {
|
|
|
|
return `${money.amount} ${money.currency}`;
|
|
|
|
}
|
|
|
|
};
|
2022-11-02 11:20:25 +00:00
|
|
|
|
|
|
|
export const formatMoneyRange = (
|
|
|
|
moneyFrom: IMoney,
|
|
|
|
moneyTo: IMoney,
|
|
|
|
locale: string,
|
|
|
|
) => {
|
|
|
|
try {
|
|
|
|
const formattedMoneyRange = (Intl.NumberFormat(locale, {
|
|
|
|
style: "currency",
|
|
|
|
currency: moneyFrom.currency,
|
|
|
|
}) as any).formatRange(moneyFrom.amount, moneyTo.amount);
|
|
|
|
// TODO: remove casting from formatRange when typescript
|
|
|
|
// is updated to 4.7 or higher
|
|
|
|
return formattedMoneyRange;
|
|
|
|
} catch (error) {
|
|
|
|
const formattedMoneyFrom = formatMoney(moneyFrom, locale);
|
|
|
|
const formattedMoneyTo = formatMoney(moneyTo, locale);
|
|
|
|
return `${formattedMoneyFrom} - ${formattedMoneyTo}`;
|
|
|
|
}
|
|
|
|
};
|