import { ItemBufferParams } from './item_buffer' ; import { TimedItemBufferParams , TimedItemBuffer } from './timed_item_buffer' ; type Fn = ( ... args : any ) => any ; export interface BatchedFunctionParams < Func extends Fn , BatchEntry > { onCall : ( ... args : Parameters < Func > ) => [ ReturnType < Func > , BatchEntry ] ; onBatch : ( items : BatchEntry [ ] ) => void ; flushOnMaxItems ? : ItemBufferParams < any > [ 'flushOnMaxItems' ] ; maxItemAge ? : TimedItemBufferParams < any > [ 'maxItemAge' ] ; } export const createBatchedFunction = < Func extends Fn , BatchEntry > ( params ) : [ Func , TimedItemBuffer < BatchEntry > ] => { const { onCall , onBatch , maxItemAge = 10 , flushOnMaxItems = 25 } = params ; const buffer = new TimedItemBuffer < BatchEntry > ( { onFlush : onBatch , maxItemAge , flushOnMaxItems , } ) ; const fn = ( ( ... args ) => { const [ result , batchEntry ] = onCall ( ... args ) ; buffer . write ( batchEntry ) ; return result ; } ) as Func ; return [ fn , buffer ] ; } ;