public
Created

  • 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
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();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.