forked from HackYourFuture/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraffic-light.js
46 lines (36 loc) · 1014 Bytes
/
traffic-light.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
"use strict";
function getCurrentState(trafficLight) {
return trafficLight.possibleStates[trafficLight.stateIndex];
}
function getNextStateIndex(trafficLight) {
const colorState = trafficLight.possibleStates[trafficLight.stateIndex];
if (colorState === 'green') {return 1;}
if (colorState === 'orange') {return 2;}
if (colorState === 'red') {return 0;}
/* This is also another solution I found:
if (trafficLight.stateIndex === 2) {
return 0;
}
else {
return trafficLight.stateIndex + 1;
}
*/
}
function waitSync(secs) {
const start = Date.now();
while (Date.now() - start < secs * 1000) {
}
}
function main() {
const trafficLight = {
possibleStates: ["green", "orange", "red"],
stateIndex: 0,
};
for (let cycle = 0; cycle < 6; cycle++) {
const currentState = getCurrentState(trafficLight);
console.log(cycle, "The traffic light is now", currentState);
waitSync(1);
trafficLight.stateIndex = getNextStateIndex(trafficLight);
}
}
main();