Skip to content

Instantly share code, notes, and snippets.

@ErfanEbrahimnia
Last active August 29, 2015 14:19
Show Gist options
  • Save ErfanEbrahimnia/c5f2a13aaff6186c8d1d to your computer and use it in GitHub Desktop.
Save ErfanEbrahimnia/c5f2a13aaff6186c8d1d to your computer and use it in GitHub Desktop.
Simple state machine with transitions
'use strict';
var _ = require('lodash');
/**
* @class StateMachine
* @constructor
*/
function StateMachine(options) {
/**
* @type {Object}
*/
this.options = options;
/**
* current state
* @type {String}
*/
this.currentState = options.state;
/**
* state transitions
* @type {Object}
*/
this.transitions = {};
}
/**
* Returns the current state of the state machine
* @method getState
*/
StateMachine.prototype.getState = function getState() {
return this.currentState;
};
/**
* merge into the internal transitions
* @method addTransitions
* @param {Object} transitions
*/
StateMachine.prototype.addTransitions = function addTransitions(transitions) {
return _.extend(this.transitions, transitions);
};
/**
* Update the current state and call the state transition method
* @method changeState
* @param {String} state
*/
StateMachine.prototype.changeState = function changeState() {
// take the given state out of the arguments array
var state = [].shift.apply(arguments);
var context = this.options.context || null;
if(!!this.transitions) {
var transition = this.transitions[this.currentState + ' > ' + state];
var fromTransition = this.transitions[this.currentState + ' >'];
var toTransition = this.transitions['> ' + state];
if (!!fromTransition) {
fromTransition.apply(context, arguments);
}
if (!!transition) {
transition.apply(context, arguments);
}
if (!!toTransition) {
toTransition.apply(context, arguments);
}
}
this.currentState = state;
};
module.exports = StateMachine;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment