import datemath from '@elastic/datemath' ; import { compact , pickBy } from 'lodash' ; import moment from 'moment' ; import { UrlParams } from './types' ; function getParsedDate ( rawDate ? , options = { } ) { if ( rawDate ) { const parsed = datemath . parse ( rawDate , options ) ; if ( parsed && parsed . isValid ( ) ) { return parsed . toDate ( ) ; } } } export function getExactDate ( rawDate ) { const isRelativeDate = rawDate . startsWith ( 'now' ) ; if ( isRelativeDate ) { const rawDateWithouRounding = rawDate . replace ( /\/([smhdw])$/ , '' ) ; return getParsedDate ( rawDateWithouRounding ) ; } return getParsedDate ( rawDate ) ; } export function getDateRange ( { state = { } , rangeFrom , rangeTo , } ) { if ( state . rangeFrom === rangeFrom && state . rangeTo === rangeTo ) { return { start : state . start , end : state . end , exactStart : state . exactStart , exactEnd : state . exactEnd , } ; } const start = getParsedDate ( rangeFrom ) ; const end = getParsedDate ( rangeTo , { roundUp : true } ) ; const exactStart = rangeFrom ? getExactDate ( rangeFrom ) : undefined ; const exactEnd = rangeTo ? getExactDate ( rangeTo ) : undefined ; if ( ! start || ! end ) { return { start : state . start , end : state . end , exactStart : state . exactStart , exactEnd : state . exactEnd , } ; } const roundedStart = moment ( start ) . startOf ( 'minute' ) ; return { start : roundedStart . toISOString ( ) , end : end . toISOString ( ) , exactStart : exactStart ?. toISOString ( ) , exactEnd : exactEnd ?. toISOString ( ) , } ; } export function toNumber ( value ? ) { if ( value !== undefined ) { return parseInt ( value , 10 ) ; } } export function toString ( value ? ) { if ( value === '' || value === 'null' || value === 'undefined' ) { return ; } return value ; } export function toBoolean ( value ? ) { return value === 'true' ; } export function getPathAsArray ( pathname = '' ) { return compact ( pathname . split ( '/' ) ) ; } export function removeUndefinedProps < T extends object > ( obj ) { return pickBy ( obj , ( value ) => value !== undefined ) ; }