Last active
October 19, 2016 11:07
-
-
Save hexode/3dc4767cd2f1bdf8f9ba 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