Logo

dev-resources.site

for different kinds of informations.

Finite-state machine example in JavaScript

Published at
7/2/2024
Categories
javascript
patterns
example
Author
artem
Categories
3 categories in total
javascript
open
patterns
open
example
open
Author
5 person written this
artem
open
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

patterns Article's
30 articles in total
Favicon
Streamlining Data Flow in Angular: The Power of the Adapter Pattern ๐Ÿ”„
Favicon
CQRS โ€” Command Query Responsibility Segregation โ€” A Java, Spring, SpringBoot, and Axon Example
Favicon
Mastering the Container-Presenter Pattern in Angular: A Deep Dive
Favicon
Repository Design Pattern, Promoting Packages via ADS, and New Arabic Article โœจ
Favicon
Flexibilidad y Escalabilidad: Usando Strategy y Factory Patterns
Favicon
Understanding Domain Events in TypeScript: Making Events Work for You
Favicon
Padrรตes de Projeto em React [HOCs, Render Props, Hooks]
Favicon
Mobile Development Platforms and software architecture pattern in mobile development
Favicon
Finite-state machine example in JavaScript
Favicon
OOP Simplified: Quick Factory Methods with Encapsulation, Abstraction, and Polymorphism in TypeScript
Favicon
Finite-state machine example in JavaScript
Favicon
How to avoid N + 1 and keep your Ruby on Rails controller clean
Favicon
Types Of Software Architecture
Favicon
Testando das trincheiras: Usando um "clock" fixo
Favicon
ยฟPOR QUร‰ no estรกs usando estos providers de Angular?
Favicon
Common and Useful Deployment Patterns
Favicon
Reusing state management: HOC vs Hook
Favicon
Understanding JavaScript Creational Patterns for Object Creation
Favicon
Understanding Design First: Principles, Patterns, and Best Practices Explained
Favicon
The Architecture Might Not Be the Problem
Favicon
Padrรฃo JumpTable com Javascript
Favicon
Explorando os Fundamentos dos Padrรตes de Projeto: Conceitos Bรกsicos
Favicon
Six Factors That Raise The Risk Of Bugs In A Codebase
Favicon
Microservices: Avoiding the Pitfalls, Embracing the Potential - A Guide to Anti-Patterns
Favicon
Android Presentation Patterns: MVI
Favicon
Entendendo o Pub/Sub com Javascript
Favicon
The Consumer Conundrum: Navigating Change in Microservices Without Gridlock
Favicon
๐—ช๐—ต๐—ฎ๐˜ ๐—ฎ๐—ฟ๐—ฒ ๐˜๐—ต๐—ฒ ๐—ฅ๐—ฒ๐—ด๐—˜๐˜… ๐—ฃ๐—ฎ๐˜๐˜๐—ฒ๐—ฟ๐—ป๐˜€?
Favicon
Using a Trait in Builder CLIs
Favicon
CLI Contexts

Featured ones: