import defaultLocale from '../locale/en-US/index' ; import type { FormatDistanceToken , Locale } from '../locale/types' ; import type { Duration } from '../types' ; const defaultFormat = [ 'years' , 'months' , 'weeks' , 'days' , 'hours' , 'minutes' , 'seconds' , ] ; interface Options { format ? : ( keyof Duration ) [ ] ; zero ? : boolean ; delimiter ? : string ; locale ? : Locale ; } name category summary description param { Duration } duration param options param { string [ ] } options . format param { boolean } options . zero param { string } options . delimiter param { Locale } options . locale - the locale object. See [Locale] https returns { string } throws example example example example example export default function formatDuration ( duration , options = { } ) { if ( arguments . length < 1 ) { throw new TypeError ( `1 argument required, but only ${ arguments . length } present` ) ; } const format = options ?. format || defaultFormat ; const locale = options ?. locale || defaultLocale ; const zero = options ?. zero || false ; const delimiter = options ?. delimiter || ' ' ; if ( ! locale . formatDistance ) { return '' ; } const result = format . reduce ( ( acc , unit ) => { const token = `x${ unit . replace ( /(^.)/ , ( m ) => m . toUpperCase ( ) ) }` as FormatDistanceToken ; const value = duration [ unit ] ; if ( typeof value === 'number' && ( zero || duration [ unit ] ) ) { return acc . concat ( locale . formatDistance ( token , value ) ) ; } return acc ; } , [ ] as string [ ] ) . join ( delimiter ) ; return result ; }