import { Message , MessageHandler , Transport } from "../types" ; export default class LocalTransport implements Transport { static create ( ) { const left = new LocalTransport ( ) ; const right = new LocalTransport ( ) ; const temp = left . send ; left . send = right . send . bind ( right ) ; right . send = temp . bind ( left ) ; return { left , right } ; } private closed : boolean = false ; private subscribers : MessageHandler [ ] = [ ] ; subscribe = ( handler ) => { if ( this . closed || this . subscribers . indexOf ( handler ) > - 1 ) { return ; } this . subscribers . push ( handler ) ; } ; unsubscribe = ( handler ) => { const i = this . subscribers . indexOf ( handler ) ; if ( i === - 1 ) { return ; } this . subscribers . splice ( i , 1 ) ; } ; send = ( message ) => { if ( this . closed ) { return ; } for ( let i = 0 ; i < this . subscribers . length ; i ++ ) { this . subscribers [ i ] ( message ) ; } } ; close ( ) { this . closed = true ; this . subscribers = [ ] ; } }