Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Created August 24, 2012 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egonelbre/3446431 to your computer and use it in GitHub Desktop.
Save egonelbre/3446431 to your computer and use it in GitHub Desktop.
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 str = '12345 + 12345';
var pos = 0;
var stk = [];
function isDigit(num){
return num >= '0' && num <= '9'
}
var transition = function(self, str, pos){
if( pos >= str.length){
self.go("done");
return
}
if( isDigit(str[pos]) ){
console.log("==> digit");
self.trigger("digit")
} else {
console.log("==> other");
self.trigger("other")
}
}
var mch = Machine('start', {
start : {
fn : function(){
console.log("start");
transition(this, str, pos);
},
tx : {
digit : "number",
other : "whitespace"
}
},
undefined : { fn : function(){ console.log("ERROR"); }},
done : { fn : function(){ console.log("DONE"); } },
whitespace: {
fn: function(){
console.log(pos);
pos += 1;
transition(this, str, pos);
},
tx : {
digit : "number",
other : "whitespace"
}
},
number: {
data : { buf : "" },
enter : function(){ this.buf = ""; },
exit : function(){
stk.push(this.buf);
console.log("TOKEN Number: " + this.buf);
},
fn: function() {
var cur = str[pos];
this.buf += cur;
pos += 1;
transition(this, str, pos);
},
tx : {
other : "whitespace"
}
}
});
for(var i = 0; i < 20; i += 1)
mch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment