Skip to content

Instantly share code, notes, and snippets.

@eugeniop
Created November 22, 2012 00:09
Show Gist options
  • Save eugeniop/4128648 to your computer and use it in GitHub Desktop.
Save eugeniop/4128648 to your computer and use it in GitHub Desktop.
A simple sattemachine
var stateMachine = require('./statemachine');
var EventOne = function(event)
{
return event == 'one';
}
var EventTwo = function(event)
{
return event == 'two';
}
var sm = new stateMachine('sm');
sm.state('one')
.when(EventOne)
.then(function(e){console.log('S1: ' + e); return 'one';})
.when(EventTwo)
.then(function(e){console.log('S1: ' + e); return 'two';})
.any()
.then(function(e){console.log('S1: (any)' + e); return 'one';});
sm.state('two')
.when(EventTwo)
.then(function(e){console.log('S2: ' + e); return 'two';})
.when(EventOne)
.then(function(e){console.log('S2: ' + e); return 'one';})
.default(function(e){console.log('S2: (default)' + e)});
sm.currentState = 'one';
sm.process('one');
sm.process('four');
sm.process('two');
sm.process('three');
sm.process('one');
sm.process('hello');
///StateEntry
function stateEntry(state,selector)
{
this.selector = selector;
this.state = state;
this.action = function() { return this.state.name; }
}
stateEntry.prototype.then = function(action)
{
this.action = action;
return this.state;
}
///State
function state(name)
{
this.stateName = name;
this.entries = [];
}
state.prototype.when = function( selector )
{
var entry = new stateEntry(this,selector);
this.entries[this.entries.length] = entry;
return entry;
}
state.prototype.any = function()
{
return this.when(function(){return true;});
}
state.prototype.default = function(action)
{
var thisState = this.stateName;
this.any()
.then( function(e){
action(e);
return thisState;
});
}
state.prototype.process = function( event )
{
for( var x = 0; x < this.entries.length; x++ )
if( this.entries[x].selector(event) )
return this.entries[x].action(event);
}
function stateMachine(name)
{
this.name = name;
this.states = [];
this.currentState = "";
}
module.exports = stateMachine;
stateMachine.prototype.state = function(stateName)
{
var st = new state(stateName);
this.states[stateName] = st;
return st;
}
stateMachine.prototype.process = function(event)
{
this.currentState = this.states[this.currentState].process(event);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment