Javascript Calculator: Plus Sign Alternatives
As I was researching my current question this article seemed to be promising but I could not figure out for myself if it was the answer to my question. So if anyone could help my t
Solution 1:
Here's a very simple calculator implementation with prototypes and a module, no eval
needed.
var calc = (function calcModule() {
function Calculator(operation) {
this.op = operation;
this._init();
}
Calculator.prototype = {
_init: function() {
this.n1 = +this.op.split(/\D/)[0];
this.n2 = +this.op.split(/\D/)[1];
this.result = this[this.op.match(/\D/)[0]]();
},
'+': function() { return this.n1 + this.n2 },
'-': function() { return this.n1 - this.n2 },
'*': function() { return this.n1 * this.n2 },
'/': function() { return this.n1 / this.n2 }
};
return function(op) {
return new Calculator(op);
};
}());
You can change what the symbols do if you want to. You use it like so:
console.log(calc('20-15').result); //=> 5
console.log(calc('15/5').result); //=> 3
...
Note that it's very simple, it'll only work with two numbers, but just so you get an idea...
Solution 2:
You could also do this:
var Atext = form.first.value.replace(/\//g,"+");
var Btext = form.second.value.replace(/\//g,"+");
Which would replace all division operators behind the scenes so that your eval will process them as addition. (So you could put 5/5/5 and get 15, or what have you.)
Post a Comment for "Javascript Calculator: Plus Sign Alternatives"