[Javascript] Intl.ListFormat

const items = [
  'Sojourner',
  'Opportunity',
  'Spirit',
  'Curiosity',
  'Perseverance',
]
const formatter = new Intl.ListFormat('en', {
  style: 'long',
  type: 'conjunction',
})
console.log(formatter.format(items))
// logs: "Sojourner, Opportunity, Spirit, Curiosity, and Perseverance"

 

See the Post

 

Typescript-ify:

// unfortunately TypeScript doesn't have Intl.ListFormat yet 😢
// so we'll just add it ourselves:
type ListFormatOptions = {
  type?: 'conjunction' | 'disjunction' | 'unit'
  style?: 'long' | 'short' | 'narrow'
  localeMatcher?: 'lookup' | 'best fit'
}
declare namespace Intl {
  class ListFormat {
    constructor(locale: string, options: ListFormatOptions)
    public format: (items: Array<string>) => string
  }
}
type ListifyOptions<ItemType> = {
  type?: ListFormatOptions['type']
  style?: ListFormatOptions['style']
  stringify?: (item: ItemType) => string
}
function listify<ItemType>(
  array: Array<ItemType>,
  {
    type = 'conjunction',
    style = 'long',
    stringify = (thing: {toString(): string}) => thing.toString(),
  }: ListifyOptions<ItemType> = {},
) {
  const stringified = array.map(item => stringify(item))
  const formatter = new Intl.ListFormat('en', {style, type})
  return formatter.format(stringified)
}
function listify(
  array,
  {conjunction = 'and ', stringify = item => item.toString()} = {},
) {
  return array.reduce((list, item, index) => {
    if (index === 0) return stringify(item)
    if (index === array.length - 1) {
      if (index === 1) return `${list} ${conjunction}${stringify(item)}`
      else return `${list}, ${conjunction}${stringify(item)}`
    }
    return `${list}, ${stringify(item)}`
  }, '')
}

 

posted @ 2021-02-21 21:49  Zhentiw  阅读(151)  评论(0)    收藏  举报