import dateMath from '@elastic/datemath' ; import { leastCommonMultiple } from './least_common_multiple' ; import { parseOpenSearchInterval } from './parse_opensearch_interval' ; returns { string } export function leastCommonInterval ( a , b ) { const { unitsMap , unitsDesc } = dateMath ; const aInt = parseOpenSearchInterval ( a ) ; const bInt = parseOpenSearchInterval ( b ) ; if ( a === b ) { return a ; } const aUnit = unitsMap [ aInt . unit ] ; const bUnit = unitsMap [ bInt . unit ] ; if ( aInt . type !== bInt . type ) { throw Error ( `Incompatible intervals: ${ a } (${ aInt . type }), ${ b } (${ bInt . type })` ) ; } if ( aInt . type === 'calendar' || bInt . type === 'calendar' ) { return aUnit . weight > bUnit . weight ? `${ aInt . value }${ aInt . unit }` : `${ bInt . value }${ bInt . unit }` ; } const aMs = aInt . value * aUnit . base ; const bMs = bInt . value * bUnit . base ; const lcmMs = leastCommonMultiple ( aMs , bMs ) ; if ( lcmMs === bMs ) { return b . replace ( /\s/g , '' ) ; } if ( lcmMs === aMs ) { return a . replace ( /\s/g , '' ) ; } const lcmUnit = unitsDesc . find ( ( unit ) => { const unitInfo = unitsMap [ unit ] ; return ! ! ( unitInfo . type !== 'calendar' && lcmMs % unitInfo . base === 0 ) ; } ) ; if ( ! lcmUnit ) { throw Error ( `Unable to find common interval for: ${ a }, ${ b }` ) ; } return `${ lcmMs / unitsMap [ lcmUnit ] . base }${ lcmUnit }` ; }