public
Last active

State Machine

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
function Machine(first, $){
var cur = {}, next = $[first];
var self = {
go : function(to){ next = next ? next : ($[to] || $.undefined); },
trigger : function(event){ var t = cur.tx && cur.tx[event]; t && self.go(t); }
};
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();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.