import { DurationInput } from './types' ; import { parse } from './parse' ; import { isZero } from './isZero' ; import { getUnitCount } from './lib/getUnitCount' ; import { UNITS_META , UNITS_META_MAP } from './lib/units' ; const joinComponents = ( component ) => component . join ( '' ) . replace ( /\./g , ',' ) ; example export const toString = ( duration ) : string => { if ( isZero ( duration ) ) { return 'P0D' ; } const parsed = { ... parse ( duration ) } ; if ( getUnitCount ( parsed ) === 1 && parsed . weeks !== 0 ) { return `P${ parsed . weeks }W` ; } const components = { period : [ ] as string [ ] , time : [ ] as string [ ] , } ; UNITS_META . forEach ( ( { unit : fromUnit , stringifyConvertTo : toUnit } ) => { if ( toUnit == null ) { return ; } const millisecondValue = parsed [ fromUnit ] * UNITS_META_MAP [ fromUnit ] . milliseconds ; parsed [ toUnit ] += millisecondValue / UNITS_META_MAP [ toUnit ] . milliseconds ; parsed [ fromUnit ] = 0 ; } ) ; UNITS_META . forEach ( ( { unit , ISOPrecision , ISOCharacter } ) => { const value = parsed [ unit ] ; if ( ISOPrecision != null && value !== 0 ) { components [ ISOPrecision ] . push ( `${ value }${ ISOCharacter }` ) ; } } ) ; let output = `P${ joinComponents ( components . period ) }` ; if ( components . time . length ) { output += `T${ joinComponents ( components . time ) }` ; } return output ; } ;