All files clockWithObserver.ts

95.65% Statements 22/23
100% Branches 0/0
91.66% Functions 11/12
95.23% Lines 20/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                    1x 3x   6x   3x 5x   10x       1x 3x 3x   3x 6x 4x       1x 2x 2x   2x 2x   4x 4x 4x              
interface AbsObserver {
    notify(t:number):void
}
 
export interface AbsObservedClock {
    reset():void  // resets the time to 0
    tick():void   // increments the time
    addObserver(obs:AbsObserver):void // 
}
 
export class ObservedClock implements AbsObservedClock {
    time: number = 0
    reset() { this.time = 0 } 
    tick() { this.time++; this.notifyAll() }     
    
    private observers: AbsObserver[] = []
    public addObserver(obs:AbsObserver){this.observers.push(obs)}
    private notifyAll() {
            this.observers.forEach(obs => obs.notify(this.time))
        }
}
 
export class ObservedClockClient implements AbsObserver {
    constructor (private theclock:AbsObservedClock) {
        theclock.addObserver(this)
    }
    private time = 0
    notify (t:number) {this.time = t}
    getTime () {return this.time}
}
 
// the Observer gets to decide what to do with the notification
export class DifferentClockClient implements AbsObserver {
    constructor (private theclock:AbsObservedClock) {
        theclock.addObserver(this)
    }
    private time = 0
    private notifications : number[] = [] // just for fun
    notify(t: number) { 
        this.notifications.push(t)
        this.time =  t * 2 }
    getTime() { return (this.time / 2) }
}