Convert Figma logo to code with AI

jakesgordon logojavascript-state-machine

A javascript finite state machine library

8,696
965
8,696
75

Top Related Projects

27,295

Actor-based state management & orchestration for complex app logic.

Quick Overview

JavaScript State Machine is a lightweight library for creating finite state machines in JavaScript. It provides a simple and intuitive API for defining states, transitions, and callbacks, making it easy to model complex behaviors and manage application state.

Pros

  • Easy to use and understand, with a clean and straightforward API
  • Lightweight and dependency-free, suitable for both browser and Node.js environments
  • Supports asynchronous transitions and lifecycle events
  • Extensible through plugins and custom visualization options

Cons

  • Limited built-in visualization options compared to some other state machine libraries
  • May require additional effort to integrate with complex application architectures
  • Documentation could be more comprehensive, especially for advanced use cases
  • Not actively maintained, with the last major update in 2018

Code Examples

  1. Creating a simple state machine:
const fsm = new StateMachine({
  init: 'solid',
  transitions: [
    { name: 'melt', from: 'solid', to: 'liquid' },
    { name: 'freeze', from: 'liquid', to: 'solid' },
    { name: 'vaporize', from: 'liquid', to: 'gas' },
    { name: 'condense', from: 'gas', to: 'liquid' }
  ],
  methods: {
    onMelt: function() { console.log('I melted') },
    onFreeze: function() { console.log('I froze') }
  }
});
  1. Transitioning between states:
fsm.melt();  // logs: 'I melted'
console.log(fsm.state);  // 'liquid'
fsm.vaporize();
console.log(fsm.state);  // 'gas'
  1. Using asynchronous transitions:
const fsm = new StateMachine({
  init: 'pending',
  transitions: [
    { name: 'resolve', from: 'pending', to: 'resolved' },
    { name: 'reject', from: 'pending', to: 'rejected' }
  ],
  methods: {
    onResolve: function() {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log('Resolved after 1 second');
          resolve();
        }, 1000);
      });
    }
  }
});

await fsm.resolve();  // logs: 'Resolved after 1 second'

Getting Started

  1. Install the library:

    npm install javascript-state-machine
    
  2. Import and use in your project:

    import StateMachine from 'javascript-state-machine';
    
    const fsm = new StateMachine({
      init: 'idle',
      transitions: [
        { name: 'start', from: 'idle', to: 'running' },
        { name: 'pause', from: 'running', to: 'paused' },
        { name: 'resume', from: 'paused', to: 'running' },
        { name: 'stop', from: ['running', 'paused'], to: 'idle' }
      ],
      methods: {
        onStart: function() { console.log('Started') },
        onStop: function() { console.log('Stopped') }
      }
    });
    
    fsm.start();  // logs: 'Started'
    console.log(fsm.state);  // 'running'
    

Competitor Comparisons

27,295

Actor-based state management & orchestration for complex app logic.

Pros of XState

  • More powerful and feature-rich, supporting hierarchical and parallel states
  • Provides visualization tools for state machines
  • Better TypeScript support and type safety

Cons of XState

  • Steeper learning curve due to more complex API
  • Larger bundle size, which may impact performance in smaller projects
  • Can be overkill for simple state management needs

Code Comparison

JavaScript State Machine:

var fsm = new StateMachine({
  init: 'solid',
  transitions: [
    { name: 'melt', from: 'solid', to: 'liquid' },
    { name: 'freeze', from: 'liquid', to: 'solid' }
  ]
});

XState:

const waterMachine = createMachine({
  id: 'water',
  initial: 'solid',
  states: {
    solid: { on: { MELT: 'liquid' } },
    liquid: { on: { FREEZE: 'solid' } }
  }
});

Summary

XState offers more advanced features and better tooling, making it suitable for complex state management scenarios. However, it comes with a steeper learning curve and larger bundle size. JavaScript State Machine is simpler and more lightweight, ideal for basic state management needs. The choice between the two depends on the project's complexity and requirements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Javascript State Machine

NPM version Build Status

A library for finite state machines.

matter state machine


NOTE for existing users

VERSION 3.0 Is a significant rewrite from earlier versions. Existing 2.x users should be sure to read the Upgrade Guide.


Installation

In a browser:

  <script src='state-machine.js'></script>

after downloading the source or the minified version

Using npm:

  npm install --save-dev javascript-state-machine

In Node.js:

  var StateMachine = require('javascript-state-machine');

Usage

A state machine can be constructed using:

  var fsm = new StateMachine({
    init: 'solid',
    transitions: [
      { name: 'melt',     from: 'solid',  to: 'liquid' },
      { name: 'freeze',   from: 'liquid', to: 'solid'  },
      { name: 'vaporize', from: 'liquid', to: 'gas'    },
      { name: 'condense', from: 'gas',    to: 'liquid' }
    ],
    methods: {
      onMelt:     function() { console.log('I melted')    },
      onFreeze:   function() { console.log('I froze')     },
      onVaporize: function() { console.log('I vaporized') },
      onCondense: function() { console.log('I condensed') }
    }
  });

... which creates an object with a current state property:

  • fsm.state

... methods to transition to a different state:

  • fsm.melt()
  • fsm.freeze()
  • fsm.vaporize()
  • fsm.condense()

... observer methods called automatically during the lifecycle of a transition:

  • onMelt()
  • onFreeze()
  • onVaporize()
  • onCondense()

... along with the following helper methods:

  • fsm.is(s) - return true if state s is the current state
  • fsm.can(t) - return true if transition t can occur from the current state
  • fsm.cannot(t) - return true if transition t cannot occur from the current state
  • fsm.transitions() - return list of transitions that are allowed from the current state
  • fsm.allTransitions() - return list of all possible transitions
  • fsm.allStates() - return list of all possible states

Terminology

A state machine consists of a set of States

  • solid
  • liquid
  • gas

A state machine changes state by using Transitions

  • melt
  • freeze
  • vaporize
  • condense

A state machine can perform actions during a transition by observing Lifecycle Events

  • onBeforeMelt
  • onAfterMelt
  • onLeaveSolid
  • onEnterLiquid
  • ...

A state machine can also have arbitrary Data and Methods.

Multiple instances of a state machine can be created using a State Machine Factory.

Documentation

Read more about

Contributing

You can Contribute to this project with issues or pull requests.

Release Notes

See RELEASE NOTES file.

License

See MIT LICENSE file.

Contact

If you have any ideas, feedback, requests or bug reports, you can reach me at jake@codeincomplete.com, or via my website: Code inComplete

NPM DownloadsLast 30 Days