added prettier and eslint for dev
This commit is contained in:
80
lib/formatters.ts
Normal file
80
lib/formatters.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
export const formatCurrency = (
|
||||
number: number,
|
||||
currency: string,
|
||||
locale: string | undefined = undefined
|
||||
): 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
|
||||
|
||||
for (let i = 0; i <= DIVISIONS.length; i++) {
|
||||
const division = DIVISIONS[i]
|
||||
if (Math.abs(duration) < division.amount)
|
||||
return RELATIVE_DATE_FORMATTER.format(Math.round(duration), division.name)
|
||||
|
||||
duration /= division.amount
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user