0.0.6 • Published 6 years ago

joes-state-machine v0.0.6

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

Joe's State Machine

A simple, easy, and versatile state machine

const {StateMachine, newState, newTransition}
  = require('joes-state-machine');

let cat = new StateMachine({
  states: [
    newState('sleepy',
      () => console.log('The cat fell asleep'),
      () => console.log('The cat was no longer asleep!')),
    newState('awake',
      () => console.log('The cat woke up!'))
  ],
  transitions: [
    newTransition('sleepy', 'awake',
      () => console.log('The cat transitioned from asleep to awake'))
  ],
  initialState: 'sleepy',
  initialOnEnter: true // Trigger the initial onEntry callback
});

cat.goto('awake');

In this case, if initialOnEnter is true, the first callback passed to the 'sleepy' state will be called when the state machine is constructed. This may not be desired, for example you may want to control when the initial callback is called. initialOnEnter defaults to false.

Another way to call the initial callback is to simply not specify the initial state in the constructor, and then later transition to the desired initial state:

let cat = new StateMachine({
  states: [
    newState('sleepy',
      () => console.log('The cat fell asleep'),
      () => console.log('The cat was no longer asleep!')),
    newState('awake',
      () => console.log('The cat woke up!'))
  ],
  transitions: [
    newTransition('sleepy', 'awake',
      () => console.log('The cat transitioned from asleep to awake'))
  ]
});

cat.goto('sleepy'); // 'The cat fell asleep'...
cat.goto('awake'); // will trigger the other callbacks

There are also shorthands for creating state machines, states, and transitions:

const {newStateMachine, ns, nt} = require('joes-state-machine');

let cat = newStateMachine(
  [
    ns('sleepy',
      () => console.log('The cat fell asleep'),
      () => console.log('The cat was no longer asleep!')),
    ns('awake', () => console.log('The cat woke up!'))
  ],
  [
    nt('sleepy', 'awake',
      () => console.log('The cat transitioned from asleep to awake'))
  ],
  'sleepy',
  true // Trigger the initial onEntry callback for the sleepy state on object construction
);

cat.goto('awake');
0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago

1.0.0

6 years ago