<!doctype html>
<script src="https://ru.js.cx/test/libs.js"></script>
<script src="test.js"></script>
<script>
const Calculator = function () {
this.methods = {
'+': (a, b) => a + b,
'-': (a, b) => a - b
};
this.calculate = function (str) {
const splitStr = str.split(' ');
let a = parseInt(splitStr[0], 10);
let opr = splitStr[1];
let b = parseInt(splitStr[2], 10);
if (!this.methods[opr] || !isFinite(a) || !isFinite(b)) {
return NaN;
}
return this.methods[opr](a, b);
};
this.addMethod = function (name, func) {
this.methods[name] = func;
};
};
let calc = new Calculator;
console.log( calc.calculate('3 + 8') );
let powerCalc = new Calculator;
powerCalc.addMethod('*', (a, b) => a * b);
powerCalc.addMethod('/', (a, b) => a / b);
powerCalc.addMethod('**', (a, b) => a ** b);
let result = powerCalc.calculate('2 ** 3');
console.log(result);
</script>
</html>
describe("Calculator", function() {
let calculator;
before(function() {
calculator = new Calculator;
});
it("calculate(12 + 34) = 46", function() {
assert.equal(calculator.calculate("12 + 34"), 46);
});
it("calculate(34 - 12) = 22", function() {
assert.equal(calculator.calculate("34 - 12"), 22);
});
it("add multiplication: calculate(2 * 3) = 6", function() {
calculator.addMethod("*", (a, b) => a * b);
assert.equal(calculator.calculate("2 * 3"), 6);
});
it("add power: calculate(2 ** 3) = 8", function() {
calculator.addMethod("**", (a, b) => a ** b);
assert.equal(calculator.calculate("2 ** 3"), 8);
});
});