Created
May 25, 2012 17:01
-
-
Save gordonbrander/2789210 to your computer and use it in GitHub Desktop.
World's Tiniest JavaScript 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
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