-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
71 lines (55 loc) · 1.94 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
var Nanobus = require('nanobus')
var assert = require('assert')
var Parallelstate = require('./parallel-state')
module.exports = Nanostate
function Nanostate (initialState, transitions) {
if (!(this instanceof Nanostate)) return new Nanostate(initialState, transitions)
assert.equal(typeof initialState, 'string', 'nanostate: initialState should be type string')
assert.equal(typeof transitions, 'object', 'nanostate: transitions should be type object')
this.transitions = transitions
this.state = initialState
this.submachines = {}
this._submachine = null
Nanobus.call(this)
}
Nanostate.prototype = Object.create(Nanobus.prototype)
Nanostate.prototype.constructor = Nanostate
Nanostate.prototype.emit = function (eventName) {
var nextState = this._next(eventName)
assert.ok(nextState, 'nanostate.emit: invalid transition' + this.state + '->' + eventName)
if (this._submachine && Object.keys(this.transitions).indexOf(nextState) !== -1) {
this._unregister()
}
this.state = nextState
Nanobus.prototype.emit.call(this, nextState)
}
Nanostate.prototype.event = function (eventName, machine) {
this.submachines[eventName] = machine
}
Nanostate.parallel = function (transitions) {
return new Parallelstate(transitions)
}
Nanostate.prototype._unregister = function () {
if (this._submachine) {
this._submachine._unregister()
this._submachine = null
}
}
Nanostate.prototype._next = function (eventName) {
if (this._submachine) {
var nextState = this._submachine._next(eventName)
if (nextState) {
return nextState
}
}
var submachine = this.submachines[eventName]
if (submachine) {
this._submachine = submachine
return submachine.state
}
if (!Object.prototype.hasOwnProperty.call(this.transitions[this.state], eventName) &&
Object.prototype.hasOwnProperty.call(this.transitions, '*')) {
return this.transitions['*'][eventName]
}
return this.transitions[this.state][eventName]
}