Created
August 9, 2011 08:12
-
-
Save stucchio/1133589 to your computer and use it in GitHub Desktop.
Javascript Finite State Machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function FiniteStateMachine(states, transitions, initialState) { | |
var state = initialState; | |
this.getState = function() { | |
return state; | |
}; | |
this.transition = function(newState) { | |
if (_.detect(transitions, function(transition) { return (transition[0] == state) && (transition[1] == newState); })) { | |
if (('onExit' in states[state]) && (typeof states[state].onExit == 'function')) { | |
states[state].onExit(); | |
} | |
state = newState; | |
if (('onEnter' in states[state]) && (typeof states[state].onEnter == 'function')) { | |
states[state].onEnter(); | |
} | |
return state; | |
} else { | |
throw "invalid transition"; | |
} | |
}; | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment