-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrafficLight.js
72 lines (57 loc) · 1.9 KB
/
trafficLight.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const TRAFFIC_LIGHT_COLORS = {
RED: 0,
YELLOW: 1,
GREEN: 2,
WHITE: 3
}
const TRAFFIC_LIGHT_COLOR_LABELS = ['red', 'yellow', 'green', 'white']
const YELLOW_DURATION = 500
class TrafficLight {
constructor(colorChangingTime) {
this.horizontalColor = TRAFFIC_LIGHT_COLORS.RED
this.verticalColor = TRAFFIC_LIGHT_COLORS.GREEN
this.colorChangingTime = colorChangingTime
this.timertTrafficLight = null
}
run() {
this._changeLight()
this.timertTrafficLight = setInterval(() => {
this._changeLight()
}, this.colorChangingTime)
}
stop() {
clearInterval(this.timertTrafficLight)
this._setVerticalGroupColor(TRAFFIC_LIGHT_COLORS.WHITE)
this._setHorizontalGroupColor(TRAFFIC_LIGHT_COLORS.WHITE)
}
_changeLight() {
this._setVerticalGroupColor(TRAFFIC_LIGHT_COLORS.YELLOW)
this._setHorizontalGroupColor(TRAFFIC_LIGHT_COLORS.YELLOW)
setTimeout(() => {
if (this.horizontalColor === TRAFFIC_LIGHT_COLORS.RED) {
this.verticalColor = TRAFFIC_LIGHT_COLORS.RED
this.horizontalColor = TRAFFIC_LIGHT_COLORS.GREEN
this._setVerticalGroupColor(TRAFFIC_LIGHT_COLORS.RED)
this._setHorizontalGroupColor(TRAFFIC_LIGHT_COLORS.GREEN)
return
}
this.verticalColor = TRAFFIC_LIGHT_COLORS.GREEN
this.horizontalColor = TRAFFIC_LIGHT_COLORS.RED
this._setVerticalGroupColor(TRAFFIC_LIGHT_COLORS.GREEN)
this._setHorizontalGroupColor(TRAFFIC_LIGHT_COLORS.RED)
}, YELLOW_DURATION)
}
_setHorizontalGroupColor(colorId) {
trafficLightHorizontalGroup.childNodes.forEach((node) => {
node.setAttribute('fill', this._getColorLabel(colorId))
})
}
_setVerticalGroupColor(colorId) {
trafficLightVerticalGroup.childNodes.forEach((node) => {
node.setAttribute('fill', this._getColorLabel(colorId))
})
}
_getColorLabel(colorId) {
return TRAFFIC_LIGHT_COLOR_LABELS[colorId]
}
}