import { memoize } from 'lodash' ; export enum TimeUnit { Minute = 'm' , Second = 's' , Hour = 'h' , Day = 'd' } const VALID_CADENCE = new Set ( Object . values ( TimeUnit ) ) ; const CADENCE_IN_MS = { [ TimeUnit . Second ] : 1000 , [ TimeUnit . Minute ] : 60 * 1000 , [ TimeUnit . Hour ] : 60 * 60 * 1000 , [ TimeUnit . Day ] : 24 * 60 * 60 * 1000 , } ; const isNumeric = ( numAsStr ) => /^\d+$/ . test ( numAsStr ) ; export const parseIntervalAsMillisecond = memoize ( ( value ) : number => { const numericAsStr = value . slice ( 0 , - 1 ) ; const numeric = parseInt ( numericAsStr , 10 ) ; const cadence = value . slice ( - 1 ) ; if ( ! VALID_CADENCE . has ( cadence as TimeUnit ) || isNaN ( numeric ) || numeric <= 0 || ! isNumeric ( numericAsStr ) ) { throw new Error ( `Invalid time value "${ value }". Time must be of the form {number}m. Example: 5m.` ) ; } return numeric * CADENCE_IN_MS [ cadence as TimeUnit ] ; } ) ; param { Date } date param { string } interval export function timePeriodBeforeDate ( date , timePeriod ) { const result = new Date ( date . valueOf ( ) ) ; const milisecFromTime = parseIntervalAsMillisecond ( timePeriod ) ; result . setMilliseconds ( result . getMilliseconds ( ) - milisecFromTime ) ; return result ; }