Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 488f725

Browse files
authored
Merge pull request #2 from SalmaIssa96/prep-question-week1-2
Solution traffic light 2
2 parents 4ecbc8b + 6132cc7 commit 488f725

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

Week1/prep-exercises/1-traffic-light/traffic-light-2.js

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,69 @@
1-
"use strict";
1+
'use strict';
22
/**
33
* The `possibleStates` property define the states (in this case: colours)
44
* in which the traffic light can be.
55
* The `stateIndex` property indicates which of the possible states is current.
66
*/
77
const trafficLight = {
8-
possibleStates: ["green", "orange", "red"],
8+
possibleStates: ['green', 'orange', 'red'],
99
stateIndex: 0,
1010
};
1111

1212
let cycle = 0;
13+
1314
while (cycle < 2) {
1415
const currentState = trafficLight.possibleStates[trafficLight.stateIndex];
15-
console.log("The traffic light is on", currentState);
16+
17+
if (currentState == 'green') {
18+
trafficLight.stateIndex = 1;
19+
} else if (currentState == 'orange') {
20+
trafficLight.stateIndex = 2;
21+
} else if (currentState == 'red') {
22+
trafficLight.stateIndex = 0;
23+
cycle++;
24+
}
25+
console.log('The traffic light is on', currentState);
1626

1727
// TODO
1828
// if the color is green, turn it orange
1929
// if the color is orange, turn it red
2030
// if the color is red, add 1 to cycles and turn it green
2131
}
2232

33+
// do while loop
34+
35+
// do {
36+
// const currentState = trafficLight.possibleStates[trafficLight.stateIndex];
37+
// if (currentState == 'green') {
38+
// trafficLight.stateIndex = 1
39+
// } else if (currentState == "orange") {
40+
// trafficLight.stateIndex = 2
41+
// } else if (currentState == 'red') {
42+
// trafficLight.stateIndex = 0
43+
// cycle++
44+
// }
45+
// console.log("The traffic light is on", currentState);
46+
47+
// } while (cycle < 2)
48+
49+
//for loop
50+
51+
// for (let i = 0; i < 2;) {
52+
// const currentState = trafficLight.possibleStates[trafficLight.stateIndex];
53+
// if (currentState == 'green') {
54+
// trafficLight.stateIndex = 1
55+
// } else if (currentState == "orange") {
56+
// trafficLight.stateIndex = 2
57+
// } else if (currentState == 'red') {
58+
// trafficLight.stateIndex = 0
59+
// i++
60+
// }
61+
// console.log("The traffic light is on", currentState);
62+
63+
// }
64+
65+
// In a for loop, I use i instead of cycle, so I treat it like a cycle. I want to increase it when the color is red.
66+
2367
/**
2468
* The output should be:
2569

0 commit comments

Comments
 (0)