Skip to content

Instantly share code, notes, and snippets.

@jeferson-sb
Last active July 29, 2022 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeferson-sb/385d83cbc8272cba2f71626072353128 to your computer and use it in GitHub Desktop.
Save jeferson-sb/385d83cbc8272cba2f71626072353128 to your computer and use it in GitHub Desktop.
const useIntl = (languageCode: string) => {
/**
* @desc Matches a list of valid locales based on BCP-47 official list
*/
const getLanguageCode = (code: string | string[]) => {
try {
const locales = Intl.getCanonicalLocales(code)
return locales
} catch (error) {
console.error(error)
}
}
const [locale] = getLanguageCode(languageCode)
/**
* @desc Format a raw number into human-readable money format
* @example toCurrency(200, { currency: 'EUR' }) // €299.99
*/
const toCurrency = (
value: number,
{ currency }: Intl.NumberFormatOptions
) => {
const format = new Intl.NumberFormat(locale, {
style: 'currency',
currency,
})
return format.format(value)
}
/**
* @desc Format a raw number into a unit format
* @example toUnit(100, { unit: 'megabyte' }) // '100 MB'
*/
const toUnit = (
raw: number,
{ unit, unitDisplay = 'short' }: Intl.NumberFormatOptions
) => {
const numberFormat = new Intl.NumberFormat(locale, {
style: 'unit',
unit,
unitDisplay,
})
return numberFormat.format(raw)
}
/**
* @desc Get the long version of a currency code
* @example currencyName('JPY') // 'Japanese Yen'
*/
const currencyName = (currency: string) => {
return new Intl.DisplayNames(locale, { type: 'currency' }).of(currency)
}
/**
* @desc Transform an array of string into a language-sensitive list
* @example listToSentence(['tom holland', 'tobey maguire', 'andrew garfield']) // 'tom holland, tobey maguire, and andrew garfield'
*/
const listToSentence = (
list: string[],
{ type = 'conjunction', ...rest }: Intl.ListFormatOptions
) => {
const listFormat = new Intl.ListFormat(locale, {
style: 'long',
type,
...rest,
})
return listFormat.format(list)
}
/**
* @desc Formats a date object into a readable string
* @example datetimeFormat(new Date()) // 'Friday, Jul 29, 2022'
*/
const datetimeFormat = (date: Date, options: Intl.DateTimeFormatOptions) => {
const format = new Intl.DateTimeFormat(locale, {
weekday: 'long',
year: 'numeric',
month: 'short',
day: '2-digit',
...options,
})
return format.format(date)
}
/**
* @desc Formats a relative time-based in a human-readable way
* @example timeFormat(-5, 'minutes') // '5 minutes ago'
*/
const timeFormat = (
value: number,
unit: Intl.RelativeTimeFormatUnit,
options: Intl.RelativeTimeFormatOptions
) => {
const format = new Intl.RelativeTimeFormat(locale, {
style: 'long',
numeric: 'auto',
...options,
})
return format.format(value, unit)
}
return {
toCurrency,
toUnit,
currencyName,
listToSentence,
datetimeFormat,
timeFormat,
}
}
export { useIntl }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment