Skip to content

Instantly share code, notes, and snippets.

@anvaka
Created November 15, 2012 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anvaka/4081581 to your computer and use it in GitHub Desktop.
Save anvaka/4081581 to your computer and use it in GitHub Desktop.
Creating Finite State Machines with VivaGraph.js
/*******************************************
* 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);
}
};
@alexbeletsky
Copy link

Really good looking piece of code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment