123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- 'use strict';
- const utils = require('./utils');
- const StateMachine = module.exports = exports = function StateMachine() {
- };
- StateMachine.ctor = function() {
- const states = [...arguments];
- const ctor = function() {
- StateMachine.apply(this, arguments);
- this.paths = {};
- this.states = {};
- this.stateNames = states;
- let i = states.length,
- state;
- while (i--) {
- state = states[i];
- this.states[state] = {};
- }
- };
- ctor.prototype = new StateMachine();
- states.forEach(function(state) {
-
- ctor.prototype[state] = function(path) {
- this._changeState(path, state);
- };
- });
- return ctor;
- };
- StateMachine.prototype._changeState = function _changeState(path, nextState) {
- const prevBucket = this.states[this.paths[path]];
- if (prevBucket) delete prevBucket[path];
- this.paths[path] = nextState;
- this.states[nextState][path] = true;
- };
- StateMachine.prototype.clear = function clear(state) {
- const keys = Object.keys(this.states[state]);
- let i = keys.length;
- let path;
- while (i--) {
- path = keys[i];
- delete this.states[state][path];
- delete this.paths[path];
- }
- };
- StateMachine.prototype.clearPath = function clearPath(path) {
- const state = this.paths[path];
- if (!state) {
- return;
- }
- delete this.paths[path];
- delete this.states[state][path];
- };
- StateMachine.prototype.some = function some() {
- const _this = this;
- const what = arguments.length ? arguments : this.stateNames;
- return Array.prototype.some.call(what, function(state) {
- return Object.keys(_this.states[state]).length;
- });
- };
- StateMachine.prototype._iter = function _iter(iterMethod) {
- return function() {
- let states = [...arguments];
- const callback = states.pop();
- if (!states.length) states = this.stateNames;
- const _this = this;
- const paths = states.reduce(function(paths, state) {
- return paths.concat(Object.keys(_this.states[state]));
- }, []);
- return paths[iterMethod](function(path, i, paths) {
- return callback(path, i, paths);
- });
- };
- };
- StateMachine.prototype.forEach = function forEach() {
- this.forEach = this._iter('forEach');
- return this.forEach.apply(this, arguments);
- };
- StateMachine.prototype.map = function map() {
- this.map = this._iter('map');
- return this.map.apply(this, arguments);
- };
|