88 lines
1.9 KiB
TypeScript
88 lines
1.9 KiB
TypeScript
export const formatCurrency = (
|
|
number: number,
|
|
currency: string,
|
|
locale: string | null
|
|
): string => {
|
|
const CURRENCY_FORMATTER = new Intl.NumberFormat(locale || '', {
|
|
currency: currency,
|
|
style: 'currency'
|
|
})
|
|
|
|
return CURRENCY_FORMATTER.format(number)
|
|
}
|
|
|
|
export const formatNumber = (
|
|
number: number,
|
|
locale: string | undefined = undefined
|
|
): string => {
|
|
const NUMBER_FORMATTER = new Intl.NumberFormat(locale)
|
|
|
|
return NUMBER_FORMATTER.format(number)
|
|
}
|
|
|
|
export const formatCompactNumber = (
|
|
number: number,
|
|
locale: string | undefined = undefined
|
|
): string => {
|
|
const COMPACT_NUMBER_FORMATTER = new Intl.NumberFormat(locale, {
|
|
notation: 'compact'
|
|
})
|
|
|
|
return COMPACT_NUMBER_FORMATTER.format(number)
|
|
}
|
|
|
|
type DivisionsT = {
|
|
amount: number
|
|
name:
|
|
| 'year'
|
|
| 'years'
|
|
| 'quarter'
|
|
| 'quarters'
|
|
| 'month'
|
|
| 'months'
|
|
| 'week'
|
|
| 'weeks'
|
|
| 'day'
|
|
| 'days'
|
|
| 'hour'
|
|
| 'hours'
|
|
| 'minute'
|
|
| 'minutes'
|
|
| 'second'
|
|
| 'seconds'
|
|
}
|
|
const DIVISIONS: DivisionsT[] = [
|
|
{ amount: 60, name: 'seconds' },
|
|
{ amount: 60, name: 'minutes' },
|
|
{ amount: 24, name: 'hours' },
|
|
{ amount: 7, name: 'days' },
|
|
{ amount: 4.34524, name: 'weeks' },
|
|
{ amount: 12, name: 'months' },
|
|
{ amount: Number.POSITIVE_INFINITY, name: 'years' }
|
|
]
|
|
export const formatRelativeDate = (
|
|
toDate: number,
|
|
fromDate: number = new Date().getSeconds(),
|
|
locale: string | undefined = undefined
|
|
): string => {
|
|
const RELATIVE_DATE_FORMATTER = new Intl.RelativeTimeFormat(locale, {
|
|
numeric: 'auto'
|
|
})
|
|
let duration = (toDate - fromDate) / 1000
|
|
let output = ''
|
|
|
|
for (let i = 0; i <= DIVISIONS.length; i++) {
|
|
const division = DIVISIONS[i]
|
|
if (Math.abs(duration) < division.amount) {
|
|
output = RELATIVE_DATE_FORMATTER.format(
|
|
Math.round(duration),
|
|
division.name
|
|
)
|
|
}
|
|
|
|
duration /= division.amount
|
|
}
|
|
|
|
return output
|
|
}
|