Guest User

Untitled

a guest
Dec 9th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. function Machine(first, $){
  2. var cur = {}, next = $[first];
  3. var self = {
  4. go : function(to){ next = next ? next : ($[to] || $.undefined); },
  5. trigger : function(event){ var t = cur.tx && cur.tx[event]; t && self.go(t); }
  6. };
  7. return function(){
  8. if(next){
  9. cur.exit && cur.exit.call(self);
  10. cur = next; next = undefined;
  11. self.__proto__ = cur.data;
  12. cur.enter && cur.enter.call(self);
  13. }
  14. cur.fn && cur.fn.call(self);
  15. };
  16. };
  17.  
  18.  
  19. var str = '12345 + 12345';
  20. var pos = 0;
  21. var stk = [];
  22.  
  23. function isDigit(num){
  24. return num >= '0' && num <= '9'
  25. }
  26.  
  27. var transition = function(self, str, pos){
  28. if( pos >= str.length){
  29. self.go("done");
  30. return
  31. }
  32. if( isDigit(str[pos]) ){
  33. console.log("==> digit");
  34. self.trigger("digit")
  35. } else {
  36. console.log("==> other");
  37. self.trigger("other")
  38. }
  39. }
  40.  
  41. var mch = Machine('start', {
  42. start : {
  43. fn : function(){
  44. console.log("start");
  45. transition(this, str, pos);
  46. },
  47. tx : {
  48. digit : "number",
  49. other : "whitespace"
  50. }
  51. },
  52. undefined : { fn : function(){ console.log("ERROR"); }},
  53. done : { fn : function(){ console.log("DONE"); } },
  54. whitespace: {
  55. fn: function(){
  56. console.log(pos);
  57. pos += 1;
  58. transition(this, str, pos);
  59. },
  60. tx : {
  61. digit : "number",
  62. other : "whitespace"
  63. }
  64. },
  65. number: {
  66. data : { buf : "" },
  67. enter : function(){ this.buf = ""; },
  68. exit : function(){
  69. stk.push(this.buf);
  70. console.log("TOKEN Number: " + this.buf);
  71. },
  72. fn: function() {
  73. var cur = str[pos];
  74. this.buf += cur;
  75. pos += 1;
  76. transition(this, str, pos);
  77. },
  78. tx : {
  79. other : "whitespace"
  80. }
  81. }
  82. });
  83.  
  84. for(var i = 0; i < 20; i += 1)
  85. mch();
Add Comment
Please, Sign In to add comment