State machine pattern in JavaScript
Level 5352 keystrokes
A traffic light object moves between red, green and yellow following a transitions table. Three chained change() calls print each transition, and the final state, red, is printed at the end.
JavaScript code
// An object that works as a small state machine for a traffic light1const trafficLight = { // The current state; it starts at red2 state: "red", // Maps each state to the next one: red -> green -> yellow -> red3 transitions: {4 red: "green",5 green: "yellow",6 yellow: "red"7 }, // Moves to the next state8 change() { // Remembers the old state for the message9 const prev = this.state; // Looks up the next state in transitions and switches to it10 this.state = this.transitions[this.state]; // Prints the transition, e.g. red -> green11 console.log(`${prev} -> ${this.state}`); // Returns the object itself so calls can be chained12 return this;13 }, // Returns the current state14 getState() {15 return this.state;16 }17};18 // Three transitions: prints red -> green, green -> yellow, yellow -> red19trafficLight.change().change().change();// After a full cycle the state is red again, so this prints red20console.log(trafficLight.getState());Output
red -> green green -> yellow yellow -> red red
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
.× 12;× 8"× 8(× 8)× 8{× 6}× 6,× 5:× 5=× 3