Skip to content
Browse files

initial

  • Loading branch information...
0 parents commit e5ea45c7ef04dbd4d77abc7c8a1cc1df19af48c6 @dominictarr committed Apr 19, 2011
Showing with 119 additions and 0 deletions.
  1. +64 −0 fsm.js
  2. +1 −0 index.js
  3. +2 −0 readme.markdown
  4. +52 −0 test/fsm.synct.js
64 fsm.js
@@ -0,0 +1,64 @@
+
+module.exports = FSM
+
+function first(obj){
+ for(var i in obj){
+ return i
+ }
+}
+
+function FSM (schema){
+ if(!(this instanceof FSM)) return new FSM (schema)
+
+ var state = first(schema)
+
+ this.getState = function (){
+ return state
+ }
+
+ this.getStates = function (){
+ var s = []
+ for(var i in schema)
+ if(!~s.indexOf(i))
+ s.push(i)
+ return s
+ }
+
+ this.sequence = function (seq){
+ var self = this
+ seq.forEach(function (e){
+ self.event(e,[])
+ })
+ return this
+ }
+
+ this.getEvents = function (){
+ var s = []
+ for(var i in schema){
+ for(var j in schema[i])
+ if(!~s.indexOf(j) && j[0] != '_')
+ s.push(j)
+ }
+ return s
+ }
+
+ function isState(e){
+ return schema[e] ? e : false
+ }
+ var isArray = Array.isArray
+
+ this.event = function (e,args){
+ args = args || []
+ var trans = schema[state][e]
+ if(isState(trans)){
+ state = trans
+ } else if (isArray(trans) && isState(trans[0])){
+ state = trans[0]
+ trans[1].apply(this,args)
+ }
+
+ if(schema[state]._in)
+ schema[state]._in()
+ return this
+ }
+}
1 index.js
@@ -0,0 +1 @@
+module.exports = require('./fsm')
2 readme.markdown
@@ -0,0 +1,2 @@
+# Finite State Machine for nodejs #
+
52 test/fsm.synct.js
@@ -0,0 +1,52 @@
+
+var FSM = require('../fsm')
+ , it = require('it-is')
+
+exports ['basic'] = function (){
+ var s2e1 = false, s2 = false
+
+ var fsm = new FSM({
+ s1: {
+ e1: 's2' //transition to state 2
+ , e2: function (){console.log('event2')}//call func but do not change state
+ }
+ , s2: {
+ _in: function (){
+ s2 = true
+ console.log('entered state2')
+ } //call func when enter state
+ , e1: ['s1', function (){
+ s2e1 = true
+ console.log('event1 in state2')
+ }]
+ }
+ })
+
+ it(fsm.getStates()).deepEqual(['s1','s2'])
+ it(fsm.getEvents()).deepEqual(['e1','e2'])
+
+ it(s2).equal(false)
+ it(fsm.getState()).equal('s1')
+ fsm.event('e1')
+ it(fsm.getState()).equal('s2')
+ it(s2).equal(true)
+ it(s2e1).equal(false)
+ fsm.event('e1')
+ it(fsm.getState()).equal('s1')
+ it(s2e1).ok()
+ //e1 then goes back to state 1.
+}
+
+exports ['sequence'] = function (){
+ var fsm = new FSM({
+ s1: {
+ e1: 's2' //transition to state 2
+ }
+ , s2: {
+ e1: ['s1', function (){
+ }]
+ }
+ })
+
+ it(fsm.sequence('e1 e2 e1 e2'.split(' ')).getState()).equal('s1')
+}

0 comments on commit e5ea45c

Please sign in to comment.
Something went wrong with that request. Please try again.