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 light
1const trafficLight = {
// The current state; it starts at red
2 state: "red",
// Maps each state to the next one: red -> green -> yellow -> red
3 transitions: {
4 red: "green",
5 green: "yellow",
6 yellow: "red"
7 },
// Moves to the next state
8 change() {
// Remembers the old state for the message
9 const prev = this.state;
// Looks up the next state in transitions and switches to it
10 this.state = this.transitions[this.state];
// Prints the transition, e.g. red -> green
11 console.log(`${prev} -> ${this.state}`);
// Returns the object itself so calls can be chained
12 return this;
13 },
// Returns the current state
14 getState() {
15 return this.state;
16 }
17};
18
// Three transitions: prints red -> green, green -> yellow, yellow -> red
19trafficLight.change().change().change();
// After a full cycle the state is red again, so this prints red
20console.log(trafficLight.getState());

Output

red -> green
green -> yellow
yellow -> red
red
Practice typing this code

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

More JavaScript examples at level 5

← JavaScript typing practice