DEV Community

Cover image for Finite-state machine example in JavaScript
Artem
Artem

Posted on

2 1

Finite-state machine example in JavaScript

What is Finite-state machine?

Context

FSM refers to classes of automata

Classes of automata: wiki

The finite state machine (FSM) is a software design pattern where a given model transitions to other behavioral states through external input.

Example using if else

Let's say we have a simple task where we check, for example, a traffic light and perform actions depending on the current state.

function trafficLightAction(color) {
  if (color === 'green') {
    console.log('Go');
  } else if (color === 'yellow') {
    console.log('Slow down');
  } else if (color === 'red') {
    console.log('Stop');
  } else {
    console.log('Invalid color');
  }
}

// Function call examples
trafficLightAction('green');  // Return: Go
trafficLightAction('yellow'); // Return: Slow down
trafficLightAction('red');    // Return: Stop
trafficLightAction('blue');   // Return: Invalid color
Enter fullscreen mode Exit fullscreen mode

Example with using Finite-state machine (FSM)

Now let's implement the same functionality using a state machine. A state machine will be an object where each key (state) is associated with a specific action.

const trafficLightFSM = {
  green: () => console.log('Go'),
  yellow: () => console.log('Slow down'),
  red: () => console.log('Stop'),
  invalid: () => console.log('Invalid color'),
};

function trafficLightActionFSM(color) {
  const action = trafficLightFSM[color] || trafficLightFSM['invalid'];
  action();
}

// Function call examples
trafficLightActionFSM('green');  // Return: Go
trafficLightActionFSM('yellow'); // Return: Slow down
trafficLightActionFSM('red');    // Return: Stop
trafficLightActionFSM('blue');   // Return: Invalid color
Enter fullscreen mode Exit fullscreen mode

Now, our traffic light will works well.

Disclaimer:
Several levels of additional tests would not hurt here, and perhaps another programming language ;)

Traffic light

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site