1
- " use strict" ;
1
+ ' use strict' ;
2
2
/**
3
3
* The `trafficLight` object is now no longer a global variable. Instead,
4
4
* it is defined in function `main()` and passed as a parameter to other
@@ -9,6 +9,8 @@ function getCurrentState(trafficLight) {
9
9
// TODO
10
10
// Should return the current state (i.e. colour) of the `trafficLight`
11
11
// object passed as a parameter.
12
+ const { stateIndex, possibleStates } = trafficLight ;
13
+ return possibleStates [ stateIndex ] ;
12
14
}
13
15
14
16
function getNextStateIndex ( trafficLight ) {
@@ -17,6 +19,9 @@ function getNextStateIndex(trafficLight) {
17
19
// - if the color is green, it will turn to orange
18
20
// - if the color is orange, it will turn to red
19
21
// - if the color is red, it will turn to green
22
+ let { stateIndex, possibleStates } = trafficLight ;
23
+ const possibleStatesLength = possibleStates . length ;
24
+ return stateIndex >= possibleStatesLength - 1 ? 0 : ++ stateIndex ;
20
25
}
21
26
22
27
// This function loops for the number of seconds specified by the `secs`
@@ -33,13 +38,13 @@ function waitSync(secs) {
33
38
34
39
function main ( ) {
35
40
const trafficLight = {
36
- possibleStates : [ " green" , " orange" , " red" ] ,
41
+ possibleStates : [ ' green' , ' orange' , ' red' ] ,
37
42
stateIndex : 0 ,
38
43
} ;
39
44
40
45
for ( let cycle = 0 ; cycle < 6 ; cycle ++ ) {
41
46
const currentState = getCurrentState ( trafficLight ) ;
42
- console . log ( cycle , " The traffic light is now" , currentState ) ;
47
+ console . log ( cycle , ' The traffic light is now' , currentState ) ;
43
48
44
49
waitSync ( 1 ) ; // Wait a second before going to the next state
45
50
trafficLight . stateIndex = getNextStateIndex ( trafficLight ) ;
0 commit comments