etsm

0.5.2 • Public • Published

MIT licensed npm version

node etsm

Tiny state machine for node, see etsm

Description

Implement a bare bones state machine in many languages. This library aim to be simple as possible and support only basic features:

  • states on object (owner)
  • optional enter/exit methods
  • virtual state user methods
  • is in
  • unrestricted transitions
  • no runtime allocation

Install

edit package.json

  "dependencies": {
    "etsm": "*.*.*"
  }  

install packages

npm install

in your js file:

var etsm = require('etsm');
//...

Or simply drop this file into your codebase: etsm.js

Example

Simple

var etsm = require('etsm');

class Foo {
    constructor() {
        this.sm = new etsm.StateMachine(this);
        this.a = new etsm.State(this.EnterA, this.ExitA);
        this.b = new etsm.State(this.EnterB, null);
    }

    EnterA(){
        process.stdout.write(' ->A ');
    }

    ExitA(){
        process.stdout.write(' A-> ');
    }

    EnterB(){
        process.stdout.write(' ->B ');
    }

    // don't implement Exit for B state
    // ExitB(){
    //     process.stdout.write(' B-> ');
    //     assert(this.sm.Transition(this.a) == false);
    // }

    Test() {
        
        this.sm.Transition(this.a);
        this.sm.Transition(this.b);
        this.sm.Transition(null);
    }    
}

foo = new Foo();
foo.Test();

Output: " ->A A-> ->B "
Sample: ab

Virtual State Methods

var etsm = require('etsm');

class FooState extends etsm.State {
    constructor(enter, exit, tick) {
        super(enter, exit);
        this.Tick = tick;
    }
}

class Foo {
    constructor() {
        this.sm = new etsm.StateMachine(this);
        this.a = new FooState(null, null, this.TickA);
        this.b = new FooState(null, null, this.TickB);
    }

    TickA(){
        process.stdout.write(' A ');
    }

    TickB(){
        process.stdout.write(' B ');
    }

    Tick(){
        if ( this.sm.current != null && this.sm.current.Tick != null)
            this.sm.current.Tick.apply(this);
    }

    Test() {
        this.Tick();

        this.sm.Transition(this.a);
        this.Tick();

        this.sm.Transition(this.b);
        this.Tick();

        this.sm.Transition(null);
        this.Tick();
    }    
}

foo = new Foo();
foo.Test();

Output: " A B "
Sample: virtual_call

Package Sidebar

Install

npm i etsm

Weekly Downloads

2

Version

0.5.2

License

MIT

Unpacked Size

9.18 kB

Total Files

8

Last publish

Collaborators

  • ethiffeault