function Calculator() {
this.addMethod = function (name, func) {
this[name] = func;
};
this.addMethod("+", (a, b) => a + b);
this.addMethod("-", (a, b) => a - b);
this.addMethod("*", (a, b) => a * b);
this.addMethod("/", (a, b) => a / b);
this.addMethod("**", (a, b) => a ** b);
this.isOperator = function (item) {
return isNaN(Number(item)) ? true : false;
};
this.priority = {'+' : 1, '-' : 1, '*' : 2, '/' : 2, '**':3};
this.isValidOper = function (op) {
if (op in this.priority) {
return true;
} else {
return false;
}
};
this.opCmp = function(op1, op2) {
return +this.priority[op1] - (+this.priority[op2]);
};
this.calculate = function (str) {
if (!str) {
return;
}
let arr = str.split(' ');
let operators = [];
let num = [];
let top = '';
while (arr.length != 0) {
top = arr.pop();
console.log("arr top: " + top);
if (this.isOperator(top)) {
if (operators.length != 0) {
if (this.opCmp(top, operators[operators.length-1]) <= 0) {
let op = operators.pop();
let a = num.pop();
let b = num.pop();
num.push(this[op](+a, +b));
arr.push(top);
} else {
operators.push(top);
}
} else {
operators.push(top);
}
} else {
num.push(top);
}
console.log("op: " + operators);
console.log("num: " + num);
}
while (operators.length != 0) {
let op = operators.pop();
let a = num.pop();
let b = num.pop();
num.push(this[op](+a, +b));
}
return num.pop();
};
}
let powerCalc = new Calculator;
let result = powerCalc.calculate("1 + 2 ** 3 * 2");
console.log( result ); // 8
result = powerCalc.calculate("1 + 2 ** 3 * 4 + 2");
console.log( result ); // 8
console