import { PlannedResponseUnit , PlannedResponseUnitType } from './type' ; export const playbackResponseUnits = async ( responseUnits , { onMessage , beforeDelay , afterDelay , onComplete , } ) => { const addDelay = ( ms ) : Promise < void > => new Promise ( ( resolve , reject ) => { setTimeout ( ( ) => { resolve ( ) ; } , ms ) ; } ) ; for ( const pru of responseUnits ) { if ( pru . type === PlannedResponseUnitType . DELAY && pru . time ) { if ( beforeDelay ) beforeDelay ( pru . time ) ; await addDelay ( pru . time ) ; if ( afterDelay ) afterDelay ( pru . time ) ; } else if ( onMessage ) onMessage ( pru . message ) ; } if ( onComplete ) onComplete ( ) ; } ; const example = [ { type : PlannedResponseUnitType . MESSAGE , message : 'Message 1' } , { type : PlannedResponseUnitType . DELAY , time : 2000 } , { type : PlannedResponseUnitType . MESSAGE , message : 'Message 2 (2 seconds later)' } , { type : PlannedResponseUnitType . DELAY , time : 1000 } , { type : PlannedResponseUnitType . MESSAGE , message : 'Message 3 (1 second later)' } , { type : PlannedResponseUnitType . MESSAGE , message : 'Message 4' } , { type : PlannedResponseUnitType . DELAY , time : 2000 } , { type : PlannedResponseUnitType . MESSAGE , message : 'Message 5 (2 seconds later)' } , { type : PlannedResponseUnitType . DELAY , time : 1000 } , { type : PlannedResponseUnitType . MESSAGE , message : 'Message 6 (1 second later)' } , ] ; export const examplePlayback = ( plannedResponse ) => { playbackResponseUnits ( plannedResponse , { beforeDelay : ( ms ) => { } , onMessage : ( message ) => { console . log ( `emitting ${ message }` ) ; } , afterDelay : ( ms ) => { } , onComplete : ( ) => { console . log ( 'completed playback' ) ; } , } ) ; } ;