Skip to content

Instantly share code, notes, and snippets.

@artlung
Created September 10, 2009 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artlung/184240 to your computer and use it in GitHub Desktop.
Save artlung/184240 to your computer and use it in GitHub Desktop.
A chainable calculator
// A chainable little calculator thingy.
var equation = {
i:0,
_int:function(x){
return parseInt(x,10);
},
set:function(x){
this.i = this._int(x);
return this;
},
plus:function(x){
this.i+=this._int(x);
return this;
},
minus:function(x){
this.i-=this._int(x);
return this;
},
times:function(x){
this.i*=this._int(x);
return this;
},
dividedBy:function(x){
x=this._int(x);
if (x===0) {
this.error('Division by zero is not possible');}
else if (this.i === 0) {
this.i = 0;
}
else {
this.i/=x;
}
return this;
},
error:function(msg){
this.i = msg;
},
toString:function(){
return this.i;
}
};
// an example equation. note that the order of operations is serial
var c = equation.set(5).plus(5).times(10).dividedBy(25).times(100).dividedBy(2); // 200
window.alert(c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment