-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstoplight.ts
28 lines (24 loc) · 875 Bytes
/
stoplight.ts
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
import { BehaviorSubject, interval, Observable } from "rxjs";
import { map, startWith, takeWhile } from "rxjs/operators";
const colors = ["green", "yellow", "red"] as const;
type StoplightColor = typeof colors[number];
export class Stoplight {
private color$: BehaviorSubject<StoplightColor>;
constructor(initialColor: StoplightColor, iterations: number = 0) {
this.color$ = new BehaviorSubject<StoplightColor>(initialColor);
let colorCounter = colors.indexOf(initialColor);
let iterationsCounter = 1;
interval(3000)
.pipe(
startWith(colorCounter),
map(() => {
this.color$.next(colors[colorCounter++ % colors.length]);
}),
takeWhile(() => iterationsCounter++ !== iterations)
)
.subscribe();
}
public getColor$(): Observable<StoplightColor> {
return this.color$.asObservable();
}
}