import { sortBy , isNumber } from 'lodash' ; import { Unit } from '@elastic/datemath' ; ts-ignore import { INTERVAL_STRING_RE } from '../../../../common/interval_regexp' ; export const ASCENDING_UNIT_ORDER = [ 'ms' , 's' , 'm' , 'h' , 'd' , 'w' , 'M' , 'y' ] ; const units = { ms : 0.001 , s : 1 , m : 60 , h : 3600 , d : 86400 , w : 86400 * 7 , M : 86400 * 7 * 4 , y : 86400 * 7 * 4 * 12 , } ; const sortedUnits = sortBy ( Object . keys ( units ) , ( key ) => units [ key ] ) ; export interface ParsedInterval { value : number ; unit : Unit ; } export const parseInterval = ( intervalString ) : ParsedInterval | undefined => { if ( intervalString ) { const matches = intervalString . match ( INTERVAL_STRING_RE ) ; if ( matches ) { return { value : Number ( matches [ 1 ] ) , unit : matches [ 2 ] as Unit , } ; } } } ; export const convertIntervalToUnit = ( intervalString , newUnit ) : ParsedInterval | undefined => { const parsedInterval = parseInterval ( intervalString ) ; if ( parsedInterval && units [ newUnit ] ) { return { value : Number ( ( ( parsedInterval . value * units [ parsedInterval . unit ! ] ) / units [ newUnit ] ) . toFixed ( 2 ) ) , unit : newUnit , } ; } } ; export const getSuitableUnit = ( intervalInSeconds ) => sortedUnits . find ( ( key , index , array ) => { const nextUnit = array [ index + 1 ] as Unit ; const isValidInput = isNumber ( intervalInSeconds ) && intervalInSeconds > 0 ; const isLastItem = index + 1 === array . length ; return ( isValidInput && ( ( intervalInSeconds >= units [ key as Unit ] && intervalInSeconds < units [ nextUnit ] ) || isLastItem ) ) ; } ) as Unit ; export const getUnitValue = ( unit ) => units [ unit ] ;