Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '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;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement