Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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();
Add Comment
Please, Sign In to add comment