I like finite state machines and I wanted to try metaprogramming in JavaScript ever since I’d seen Adam McCrea presentation on the topic.
The result is an FSM builder in JavaScript. Machine descriptions look like my test machine here:
var Machine = FSM.build(function(fsm) { with (fsm) {
onUnexpectedEvent(function() { ... });
state('start', 'initial')
.event('go')
.goesTo('middle')
.doing(function() { ... })
.doing('phew')
.event('run')
.goesTo('finish')
.onExiting(function() { ... });
state('middle')
.onUnexpectedEvent(function() { ... })
.onEntering(function() { ... })
.event('back')
.goesTo('start')
.onlyIf(function() { return true_or_false })
.event('go')
.goesTo('finish');
state('finish', 'final');
}});
function TestMachine() {}
// amend TestMachine.prototype here all the way you want
TestMachine.prototype.phew = function() { ... };
TestMachine.prototype = new Machine(TestMachine.prototype);
There’s no documentation yet, but thorough unit testsspecs
using Nicolás Sanguinetti’s very nice js-spec framework.
Something to look at:
The script is meant to be usable independently of and play nicely with any other libraries.
The manner in which an FSM is attached to classes/objects is still rather convoluted. The general idea is that it (a) should be possible to insert the FSM as the first link in the prototype chain and (b) should be possible to directly attach it to an existing object. I’d appreciate suggestions how to make this nice and shiny.