Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created May 25, 2012 17:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/2789210 to your computer and use it in GitHub Desktop.
Save gordonbrander/2789210 to your computer and use it in GitHub Desktop.
World's Tiniest JavaScript State Machine
var StateMachine = {
// Register valid states for this object.
__states__: {
'success': ['failure'],
'failure': ['success']
},
// Set initial state.
__state__: 'success',
// Get or set the state for this event.
state: function (state) {
var nowState = this.__state__;
// If it's a state `get`, or there is no change, return the value.
if (!state || nowState === state) return nowState;
var states = this.__states__;
var transitions = states[nowState];
// Check if this is a valid transition.
if (
// If the state given does not show up in the registry of valid states
!states[state] ||
(
// ...or if the transition requested is invalid
transitions.indexOf(state) === -1 &&
// ...and there is no wildcard operator (transition to any)
transitions.indexOf('*') === -1
)
) throw new Error('Invalid state transition');
return this.__state__ = state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment