Human APIs

612 days ago, 0 views.

Title Format

I tend to format my styles. Although you can do that following different criteria, my main criteria is aesthetic

I found title very useful for that:

const title = require('title')

title('noW deSktop and now cLI are prODUCts of zeIt')

// Will result in:
// "Now Desktop and Now CLI Are Products of ZEIT"

In addition, I created a alfred-title for create format titles on the fly using Alfred

Alternatives

Date Format

Internationalization is difficult to get right at the best of times, luckily there is a well supported API for it now in most browsers.

The method Object.prototype.toLocaleString() will format the current Number/Date/Object state into an international string locale representation.

const formatDate = ((date = new Date()),
({ lang = 'en-us', month = 'short', day = 'numeric', year = 'numeric' } = {}) =>
  new Date(date).toLocaleString(lang, { month, day, year }))

Using it on action

formatDate() // 'Dec 6, 2018'
formatDate(new Date()) // 'Dec 6, 2018'

Alternatives

Relative Time Format

The new Intl API introduces .RelativeTimeFormat for formatting time.

const formatTime = (
  date1 = new Date(),
  date2 = new Date(),
  { lang = 'en-us', unit = 'seconds', ...opts } = {}
) => new Intl.RelativeTimeFormat(lang, opts).format(date2 - date1, unit)

Although it looks promising, still it’s an early stage.

formatTime() // "in 0 seconds"
formatTime(new Date('December 17, 1995 03:24:00'), new Date('December 17, 1995 03:24:00')) // "in 0 seconds"
formatTime(new Date('December 17, 1995 03:24:00'), new Date('December 18, 1995 03:24:00')) // "in 86,400,000 seconds"
formatTime(new Date('December 17, 1995 03:24:00'), new Date('December 18, 1995 03:24:00'), { unit: 'days' }) // "in 86,400,000 days, WTF"

Unfortunatly, it hasn’t been designed for calculating time difference.

Alternatives

Number Format

The same approach could be used for format a Number:

const formatNumber = ({ style = 'currency', currency = 'CAD' } = {}) => (
  n,
  lang = 'en-US'
) => n.toLocaleString('de-DE', { style, currency })

Using it on action

const formatter = formatNumber()
const amount = 1034532

formatter(1034532) // 🇺🇸 USA
formatter(1034532, 'de-DE') // 🇩🇪 Germany
formatter(1034532, 'ar-EG') // 🇺🇪🇬 Egypt

How to Choose language

You can use the browser for getting the user language preference

const locale = navigator.language || navigator.userLanguage || 'en-US'

That’s could be a good point to start. Next step could remember the user preference and store it associated with the user profile settings.

Alternatives

List Format

const listFormat = (list, { lang = 'en-us', ...opts } = {}) => new Intl.ListFormat(lang, opts).format(list)

listFormat(['Paco']) // "Paco"
listFormat(['Paco', 'Pepe']) // "Paco and Pepe"
listFormat(['Paco', 'Pepe']) // "Paco and Pepe"
listFormat(['Paco', 'Pepe'], { type: 'disjunction' }) // "Paco or Pepe"

Alternatives

Bibliography

Kiko Beats

Kiko Beats