Skip to content

Instantly share code, notes, and snippets.

@toadkicker
Forked from egonelbre/gist:3437746
Created August 24, 2012 05:17
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 toadkicker/3445740 to your computer and use it in GitHub Desktop.
Save toadkicker/3445740 to your computer and use it in GitHub Desktop.
State Machine
function Machine(first, $){
var cur = {}, next = $[first];
var self = {
go : function(to){ next = next ? next : ($[to] || $.undefined); },
trigger : function(event){ self.go( cur.tx && cur.tx[event] ); }
};
return function(){
if(next){
cur.exit && cur.exit.call(self);
cur = next; next = undefined;
self.__proto__ = cur.data;
cur.enter && cur.enter.call(self);
}
cur.fn && cur.fn.call(self);
};
};
var m = Machine("tick", {
undefined : {
fn : function(){
console.log("ERROR: NO STATE!");
this.trigger("recover");
},
tx : {
recover : "tick"
}
},
tick : {
enter : function(){
console.log("entered tick");
},
fn : function(){
console.log("tick");
this.go("tock");
}
},
tock : {
data : {
counter : 0
},
exit : function(){
this.counter += 1;
},
fn : function(){
this.counter += 1;
console.log("tock : " + this.counter);
if(this.counter > 5)
this.go("invalid");
if(this.counter > 3)
this.trigger("forward");
},
tx : {
forward : "tick"
}
}
});
console.log("=========================");
for(var i = 0; i < 15; i += 1)
m();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment