-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
62 lines (56 loc) · 1.68 KB
/
scripts.js
File metadata and controls
62 lines (56 loc) · 1.68 KB
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
(function() {
"use strict";
class Light {
activate() {
this.light.classList.add("active");
}
deactivate() {
this.light.classList.remove("active");
}
constructor(light, lightLength) {
this.light = light;
this.lightLength = lightLength;
}
}
class TrafficLight {
currentLightIsTheLastLight() {
return this.currentLightIndex >= this.lights.length - 1;
}
cycleLights(){
this.currentLight.deactivate();
if (this.currentLightIsTheLastLight()) {
this.currentLightIndex = 0;
} else {
this.currentLightIndex++;
}
// update current light
this.currentLight = this.lights[this.currentLightIndex];
this.currentLightLength = this.currentLight.lightLength;
this.currentLight.activate();
}
constructor(lights) {
this.lights = lights;
this.currentLightIndex = 0;
this.currentLight = this.lights[this.currentLightIndex];
this.currentLightLength = this.currentLight.lightLength;
}
}
class TrafficLightScheduler {
schedule(trafficLight) {
let lightLength = trafficLight.currentLightLength;
window.setTimeout(
function() {
trafficLight.cycleLights();
this.schedule(trafficLight);
}.bind(this),
lightLength
);
}
}
let lightGo = new Light(document.getElementById("lightGo"), 4500);
let lightWarn = new Light(document.getElementById("lightWarn"), 2250);
let lightStop = new Light(document.getElementById("lightStop"), 4500);
let lights = [lightGo, lightWarn, lightStop];
let trafficLight = new TrafficLight(lights);
new TrafficLightScheduler().schedule(trafficLight);
})();