fsm-flow

A stream-ready finite state machine implementation


Keywords
fsm, stream, generator
License
MIT
Install
npm install fsm-flow@0.3.1

Documentation

fsm-flow

build status Coverage Status

A stream friendly Finite State Machine implementation.

Consider the following FSM map representation:

const stateMap = {
  ice: {heat: 'water', consume: null},
  water: {heat: 'steam', cold: 'ice', consume: null},
  steam: {cold: 'water', consume: null},
};

Below is an usual FSM example, nothing new.

const FSM = require('fsm-flow').FSM;

// Create a simple machine from a map and a initial state
var fsm = new FSM(stateMap, 'water');

// Evolve the machine
fsm.touch('heat'); // steam
fsm.touch('cold'); // water
fsm.touch('cold'); // ice

// Handle state changes normally.
fsm.on('changed', function(nv, ov){
  // Do your thing.
});

Now a more interesting stream capable FSM example (stream interface):

const FSM = require('fsm-flow').FlowFSM;

// Create a simple machine from a map and a initial state
var fsm = new FSM(stateMap, 'water');

// Create some dummy Readable stream
var events = ['heat', 'heat', 'cold', 'cold', 'consume'];

var eventSource = require('stream').Readable({
  read: function(n) {
    this.push(events.shift());
  }
});

// Use the machine as a stream pipeline stage.
eventSource.pipe(fsm).pipe(process.stdout);