New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

async-state-machine

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

async-state-machine

An Asynchronous State Machine Implementation written in Javascript

  • 1.2.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Async Js State Machine

This is a package that uses the state machine pattern in an asynchronous manner.

This allows us to do some cool things in our code and extends the capabilities of state machines to not have to rely on synchronous steps.

Basic Overview of available Objects

State

State's are your big

To set new states-

const OffState = Object.create(State)
  .setName('off')
  .onExit(() => console.log('Leaving off State'))
  .onEntry(() => console.log('Switching Off'))
  .onSuccess(() => console.log('State is now off'));

const OnState = Object.create(State).setName('on');

The lifecycles methods onEntry, onExit, and onSuccess are all optional.

Available Methods with State Object
nameparamsreturnsdescription
setNamestringselfSet name of current state object
setOnEntryfunction (async optional)selfSet function to be fired when state is entered
setOnExitfunction (async optional)selfSet function to be fired when state is left
setOnSuccessfunction (async optional)selfSet function to be fired when state has changed

Transition

A transition is a simple object which only contains it's name and conditions

If we wanted to create a transition which only fires when the sky is blue we can say

const switch_off = Object.create(Transition)
  .setName('switch_off')
  .addCondition((context, params) => params.heat === 100);

but typically your transition might be as simple as

const switch_on = Object.create(Transition).setName('switch_on');

I've opted to prefer to use Object.create(Transition) for the more simple objects versus the class syntax new Transition() as I don't believe a Transition needs to be a class.

This is a personaly preferance and if there is a case made for Transition's being classes we can go that route.

Available Methods with Transition Object
nameparamsreturnsdescription
setNamestringselfSet the name for this state
addConditioncondition: () => booleanselfAdds a new condition for this transition

Edge

An edge is defined as:

Edge.new()
  .from([LIST, OF, FROM, STATES])
  .to(SINGLE_TO_STATE)
  .with(name_of_transition);

Edges are used to define your state machine steps, where each step is a new edge- for example given a simple state graph:

OFF_STATE (switch_on)-> ON_STATE (switch_off)-> OFF_STATE

We can define this with the two edges being:

const OFF_TO_ON = Edge.new().from([OFF_STATE]).to(ON_STATE).with(switch_on)
const ON_TO_OFF = Edge.new().from([ON_STATE]).to(OFF_STATE).with(switch_off)
Available Methods with Edge Object
nameparamsreturnsdescription
new-new Edge objectReturn a new Edge Object
fromfromStates: ArrayselfSet from states
totoState: StateObjectselfSet to state
transitiontransition: StateObjectselfSet transition applicable to this edge
withtransition: StateObjectselfSet transition applicable to this edge

Machine

From the Machine class we can add our edges

const MyMachine = new Machine();
MyMachine.registerEdge(OFF_TO_ON)
  .registerEdge(ON_TO_OFF)
  .setInitialState(OFF);

To then trigger a transition we simple use

MyMachine.triggerTransition(switch_off);
Available Methods with Machine Class
nameparamsreturnsdescription
getTransitionsnoneArrayReturns available transitions from this state
getStatenonestringReturns current state
setDataGetterfunctionselfpassed in function is bound to context of Machine and is called whene data is returned
setInitialStatestate: StateObject, params: object, delayMachineStart: booleanselfset's state which machine should start at, optionally do not start machine here
triggerTransitiontransition: TransitionObjectPromiseTransitions to next state
registerEdgeedge: EdgeObjectselfRegister a new Edge onto the Machine
carrynoneselfUseful when dot chaining
startparams?: ObjectPromiseTransitions to initial state

Usage with Redux

import Machine from 'async-state-machine';
import redux from '../store';

class ReduxMachine extends Machine {
  reduxEnabled: boolean;
  machineKey: string;

  constructor(reduxEntry: string | void, enableLog: boolean = false) {
    super(enableLog);
    this.reduxEnabled = false;
    if (reduxEntry !== null) {
      // add entry as soon as class is created
      this.redux(reduxEntry);
    }
  }

  redux(name: string) {
    // add entry as soon as class is created
    this.machineKey = name;
    redux.dispatch({
      type: 'REGISTER_REDUX_MACHINE',
      payload: { machine: this.machineKey, newState: '' },
    });
    this.reduxEnabled = true;
  }

  storeRedux(newState) {
    if (this.reduxEnabled) {
      redux.dispatch({
        type: 'UPDATE_REDUX_MACHINE',
        payload: { machine: this.machineKey, newState },
      });
    }
  }

  setState(nextState: string) {
    super.setState(nextState);
    this.storeRedux(nextState.toString());
  }
}

export default ReduxMachine;

Keywords

FAQs

Package last updated on 29 May 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc