-
Notifications
You must be signed in to change notification settings - Fork 0
/
week2.js
81 lines (66 loc) · 2.21 KB
/
week2.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
73
74
75
76
77
78
79
80
81
"use strict";
/**
* The `trafficLight` object is now no longer a global variable. Instead,
* it is defined in function `main()` and passed as a parameter to other
* functions, as and when needed.
*/
function getCurrentState(trafficLight) {
// TODO
// Should return the current state (i.e. colour) of the `trafficLight`
const possibleStates = trafficLight.possibleStates;
const currentIndex = trafficLight.stateIndex;
const currentState = possibleStates[currentIndex];
return currentState;
// object passed as a parameter.
}
function getNextStateIndex(trafficLight) {
// TODO
// Return the index of the next state of the `trafficLight` such that:
// - if the color is green, it will turn to orange
// - if the color is orange, it will turn to red
// - if the color is red, it will turn to green
const possibleStates = trafficLight.possibleStates;
const currentIndex = trafficLight.stateIndex;
if(currentIndex < possibleStates.length - 1 ){
for(let i = 0; i < possibleStates.length; i++){
if(possibleStates[i] == possibleStates[currentIndex]){
return i+1;
}
}
}else{
return 0;
}
}
// This function loops for the number of seconds specified by the `secs`
// parameter and then returns.
// IMPORTANT: This is not the recommended way to implement 'waiting' in
// JavaScript. You will learn better ways of doing this when you learn about
// asynchronous code.
function waitSync(secs) {
const start = Date.now();
while (Date.now() - start < secs * 1000) {
// nothing do to here
}
}
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); // Wait a second before going to the next state
trafficLight.stateIndex = getNextStateIndex(trafficLight);
}
}
main();
/**
* The output should be:
0 The traffic light is now green
1 The traffic light is now orange
2 The traffic light is now red
3 The traffic light is now green
4 The traffic light is now orange
5 The traffic light is now red
*/