// one().plus().two().equals(); // 3
// two().plus().two().equals(); // 4
// one().one().minus().two().equals(); // 9
// one().plus().one()
// two
// minus
// plus
// equals
class Calculator {
result;
opOrder = [];
constructor(order) { this.opOrder = order }
one() {
this.opOrder.push(1)
return new Calculator(this.opOrder)
}
two() {
this.opOrder.push(2)
return new Calculator(this.opOrder)
}
minus() {
this.opOrder.push('-')
return new Calculator(this.opOrder)
}
plus() {
this.opOrder.push('+')
return new Calculator(this.opOrder)
}
equals() {
let num1 = '';
let num2 = '';
let expression = [];
let result;
for (let i=0; i<this.opOrder.length; ++i) {
if (!['+', '-'].includes(this.opOrder[i])) {
if (expression.length === 2) num2 += this.opOrder[i];
else num1 += this.opOrder[i];
} else if (expression.length !== 2) {
expression.push(num1);
expression.push(this.opOrder[i]);
}
if (num2 !== '' && (['+', '-'].includes(this.opOrder[i]) && expression.length === 2) || i === this.opOrder.length-1) {
expression.push(num2);
if (expression[1] === '+')
result = Number(expression[0])+ Number(expression[2])
else if (expression[1] === '-') {
result = Number(expression[0]) - Number(expression[2])
}
expression = [String(result), this.opOrder[i]];
num1 = String(result);
num2 = '';
}
}
console.log(result);
}
}
let cal = new Calculator([]);
const ans = cal.one().one().minus().two().plus().one().one().equals()