All files TrafficLight.ts

90.9% Statements 20/22
75% Branches 12/16
100% Functions 4/4
90.9% Lines 20/22

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 50 51    1x 6x   4x   1x   1x           1x 6x   6x       6x 6x 4x   1x 1x   1x 1x   2x 2x         2x         6x       4x      
export type Color = 'red' | 'green' | 'yellow';
 
export function colorAtNextSecond(color: Color, time: number): Color {
  switch (color) {
    case 'red':
      return time === 1 ? 'green' : 'red';
    case 'yellow':
      return time === 1 ? 'red' : 'yellow';
    case 'green':
      return time === 1 ? 'yellow' : 'green';
    default:
      throw new Error("This error shouldn't occur.");
  }
}
 
export class TrafficLight {
  color: Color = 'red';
 
  timeLeft = 20;
 
  /* simulate one second passing */
  public tick() {
    this.color = colorAtNextSecond(this.color, this.timeLeft);
    if (this.timeLeft === 1) {
      switch (this.color) {
        case 'red':
          this.timeLeft = 20;
          break;
        case 'yellow':
          this.timeLeft = 5;
          break;
        case 'green':
          this.timeLeft = 15;
          break;
        default:
          throw new Error("This error shouldn't occur.");
      }
    } else {
      this.timeLeft -= 1;
    }
  }
 
  public setTime(t: number) {
    this.timeLeft = t;
  }
 
  public getColor() {
    return this.color;
  }
}