-
-
Save nikitalarionov/ec7722552dc957d51ce2fd6d192dbc4f to your computer and use it in GitHub Desktop.
Simple fsm
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 fsm = (function() { | |
function transition(name, from, to) { | |
this.transitions[name] = {name: name, from: from, to: to}; | |
return this; | |
} | |
function init(state) { | |
this.initState = state; | |
return this; | |
} | |
function isTransitionAllowed(transition, state) { | |
var from = transition.from; | |
return from === state || from === '*'; | |
} | |
function camelize(string) { | |
return string.slice(0, 1).toUpperCase() + string.slice(1); | |
} | |
return function() { | |
function fsm(name, target) { | |
target = target || this; | |
var state = target.__state || fsm.initState; | |
var transition = fsm.transitions[name]; | |
if (!transition) { | |
throw new Error('No such transition'); | |
} | |
if (!isTransitionAllowed(transition, state)) { | |
throw new Error('Transition is prohibited'); | |
} | |
target.__state = transition.to; | |
target['onState' + camelize(transition.to)](transition); | |
} | |
fsm.transitions = {}; | |
fsm.initState = null; | |
fsm.transition = transition; | |
fsm.init = init; | |
return fsm; | |
}; | |
})(); | |
var lampController = fsm() | |
.init('off') | |
.transition('enable', 'off', 'on') | |
.transition('disable', 'on', 'off'); | |
var lamp = { | |
controller: lampController, | |
onStateOff: function() { | |
console.log('OFF'); | |
}, | |
onStateOn: function() { | |
console.log('ON'); | |
} | |
}; | |
lamp.controller('enable'); | |
lamp.controller('disable'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment