import stats from 'stats-lite' ; import { JsonObject } from '@kbn/utility-types' ; import { isUndefined , countBy , mapValues } from 'lodash' ; export interface AveragedStat extends JsonObject { p50 : number ; p90 : number ; p95 : number ; p99 : number ; } export function calculateRunningAverage ( values ) { return { p50 : stats . percentile ( values , 0.5 ) , p90 : stats . percentile ( values , 0.9 ) , p95 : stats . percentile ( values , 0.95 ) , p99 : stats . percentile ( values , 0.99 ) , } ; } param values export function calculateFrequency < T > ( values ) { return values . length ? mapValues ( countBy ( values ) , ( count ) => Math . round ( ( count * 100 ) / values . length ) ) : { } ; } /**
 * Utility to keep track of a bounded array of values which changes over time
 * dropping older values as they slide out of the window we wish to track
 */ export function createRunningAveragedStat < T > ( runningAverageWindowSize ) { const list = new Array < T > ( ) ; return ( value ? ) => { if ( ! isUndefined ( value ) ) { if ( list . length === runningAverageWindowSize ) { list . shift ( ) ; } list . push ( value ) ; } return [ ... list ] ; } ; } export function createMapOfRunningAveragedStats < T > ( runningAverageWindowSize ) { const mappedQueue = { } ; const asRecordOfValues = ( ) => mapValues ( mappedQueue , ( queue ) => queue ( ) ) ; return ( key ? , value ? ) => { if ( ! isUndefined ( key ) ) { mappedQueue [ key ] = mappedQueue [ key ] ?? createRunningAveragedStat ( runningAverageWindowSize ) ; mappedQueue [ key ] ( value ) ; } return asRecordOfValues ( ) ; } ; }