Created
November 15, 2012 21:55
-
-
Save anvaka/4081581 to your computer and use it in GitHub Desktop.
Creating Finite State Machines with VivaGraph.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************* | |
* Usage: | |
* | |
* var fsm = new FiniteStateMachine(), | |
* | |
* fsm.from('state1') | |
* .goTo('state2').when(regex1) | |
* .goTo('state3').when(regex2); | |
* fsm.from('state2') | |
* .goTo('state2').when(regex2); | |
* | |
* fsm.start('state1') // Defining starting state is state1 | |
* // running string input through FSM. | |
* for (var i = 0; i < input.length; ++i) { | |
* if (fsm.step(input[i])) { all is good, state is valid } else { invalid input } | |
*/ | |
var FiniteStateMachine = function() { | |
this.graph = Viva.Graph.graph(); | |
}; | |
FiniteStateMachine.prototype = { | |
from : function (fromStateName) { | |
var that = this, | |
stateDescription = { | |
goTo : function(toStateName) { | |
return { | |
when : function (predicate) { | |
that.graph.addLink(fromStateName, toStateName, predicate); | |
return stateDescription; | |
} | |
}; | |
} | |
}; | |
return stateDescription; | |
}, | |
start : function (startState) { | |
this.currentNode = this.start = startState; | |
}, | |
reset : function () { | |
this.currentNode = this.start; | |
}, | |
step : function (input) { | |
var links = this.graph.getLinks(this.currentNode), | |
result = false; | |
for(var i = 0; i < links.length; ++i) { | |
if (links[i].fromId === this.currentNode && this.predicate(links[i].data, input)) { | |
this.currentNode = links[i].toId; | |
result = true; | |
break; | |
} | |
} | |
return result; | |
}, | |
predicate : function(linkPredicate, input) { | |
// assuming linkPredicate is a regex, but could be anything in future: | |
return linkPredicate.test(input); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really good looking piece of code.