import { UNITS_META_MAP_LITERAL , ZERO , UnitKey } from './lib/units' ; import { Duration , DurationInput , DateInput } from './types' ; import { between } from './between' ; import { apply } from './apply' ; import { toMilliseconds , toMonths } from './toUnit' ; import { parse } from './parse' ; const createUnitsNormalizer = < T extends UnitKey > ( keys , getDivisor ) => { return ( duration , remaining ) => { const output = { ... duration } ; keys . forEach ( unit => { const divisor = getDivisor ( unit ) ; output [ unit ] = ~ ~ ( remaining / divisor ) ; remaining -= output [ unit ] * divisor ; } ) ; return output ; } ; } ; const yearMonthNormalizer = createUnitsNormalizer ( [ 'years' , 'months' ] , unit => UNITS_META_MAP_LITERAL [ unit ] . months ) ; const dayAndTimeNormalizer = createUnitsNormalizer ( [ 'days' , 'hours' , 'minutes' , 'seconds' , 'milliseconds' ] , unit => UNITS_META_MAP_LITERAL [ unit ] . milliseconds ) ; const baseNormalizer = ( duration ) : Duration => { const { years , months , weeks , days , ... rest } = parse ( duration ) ; let output = { ... ZERO } ; output = yearMonthNormalizer ( output , toMonths ( { years , months } ) ) ; output = dayAndTimeNormalizer ( output , toMilliseconds ( { ... rest , days : days + ( weeks * 7 ) } ) ) ; return output ; } ; example export const normalize = ( duration , referenceDate ? ) : Duration => { const durationToNormalize = referenceDate != null ? between ( referenceDate , apply ( referenceDate , duration ) ) : duration ; return baseNormalizer ( durationToNormalize ) ; } ;