number automata in js
//number automata implementation
/* A number automatan, is a machine which holds one state, a number. It
is a conjoining of two seperate machines. One is the state of it's acceptance,
be it addition, "+", subtraction"-", and so on. These allow other number symbols to be input,
and change the state of the machine.*/
var NumberMach = (function(){
//object to hold transition functions
var States = {
"+":function(obj, val){
obj.state += val;
},
"-":function(obj, val){
obj.state -= val;
},
"*":function(obj, val){
obj.state *= val;
},
"/":function(obj, val){
obj.state /= val;
},
"//":function(obj, val){
obj.state = Math.floor(obj.state / val);
},
"%":function(obj, val){
obj.state %= val;
}
};
function NumberMach(state, mode){
this.state = state;
this.mode = mode;
}
//function that takes input in form of either a number or a different transition
//function mode as input
NumberMach.prototype.input = function(code){
var numresult = parseInt(code);
if(isNaN(numresult)){
if(code in States){
this.mode = code;
}
}
else {
States[this.mode](this, numresult);
}
};
return NumberMach;
})();
/* var b = new NumberMach(0, "+");
b.input("55")
b
=> { state: 55, mode: '+' }
b.input("5")
b
=> { state: 60, mode: '+' }
b.input("-")
b
=> { state: 60, mode: '-' }
b.input("5")
b
=> { state: 55, mode: '-' }
b.input("55")
b
=> { state: 0, mode: '-' }*/