Skip to content

Instantly share code, notes, and snippets.

@Kreijstal
Created August 7, 2014 23:23
Show Gist options
  • Save Kreijstal/590d37e7f02b5a2d7f9b to your computer and use it in GitHub Desktop.
Save Kreijstal/590d37e7f02b5a2d7f9b to your computer and use it in GitHub Desktop.
//States
var states = [{
'name': 'working',
'initial': true,
'events': {
'bored': 'coffee',
'call_for_meeting': 'meeting',
}
}, {
'name': 'coffee',
'events': {
'break_over': 'working',
'call_for_meeting': 'meeting'
}
}, {
'name': 'meeting',
'events': {
'meetings_over': 'working'
}
}, ];
function StateMachine(states) {
this.states = states;
this.indexes = {};
for (var i = 0; i < this.states.length; i++) {
this.indexes[this.states[i].name] = i;
if (this.states[i].initial) {
this.currentState = this.states[i];
}
}
};
StateMachine.prototype.consumeEvent = function (e) {
if (this.currentState.events[e]) {
this.currentState = this.states[this.indexes[this.currentState.events[e]]];
}
}
StateMachine.prototype.getStatus = function () {
return this.currentState.name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment