<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function Calculator() {
this.methods = {
"-": function(a, b) {
return a - b;
},
"+": function(a, b) {
return a + b;
}
};
this.calculate = function(str) {
var split = str.split(' '),
a = split[0],
op = split[1],
b = split[2]
if(!this.methods[op] || !isNumeric(a) || !isNumeric(b)) {
return NaN;
}
return this.methods[op](+a, +b);
}
this.addMethod = function(name, func) {
this.methods[name] = func;
};
}
var calc = new Calculator;
calc.addMethod("*", function(a, b) {
return a * b;
});
calc.addMethod("/", function(a, b) {
return a / b;
});
calc.addMethod("**", function(a, b) {
return Math.pow(a, b);
});
var result = calc.calculate("2 ** 3");
alert(result); // 8
</script>
</body>
</html>