112 lines
2.6 KiB
JavaScript
112 lines
2.6 KiB
JavaScript
import Stack from "./stack.mjs";
|
|
|
|
function infixToPostfix(infixExpression) {
|
|
const stack1 = new Stack();
|
|
const stack2 = new Stack();
|
|
|
|
function warOperator(operator1, operator2) {
|
|
if (operator2 === undefined || operator2 === "(") {
|
|
stack1.push(operator1);
|
|
} else {
|
|
if (["x", "/"].includes(operator1) && ["+", "-"].includes(operator2)) {
|
|
stack1.push(operator1);
|
|
} else {
|
|
const top = stack1.pop();
|
|
stack2.push(top);
|
|
const nextOperator = stack1.peek();
|
|
warOperator(operator1, nextOperator);
|
|
}
|
|
}
|
|
}
|
|
|
|
const dealInfixExpression = infixExpression.replaceAll(" ", "");
|
|
|
|
let numStr = "";
|
|
for (let i = 0; i < dealInfixExpression.length; i++) {
|
|
const char = dealInfixExpression[i];
|
|
if (["+", "-", "x", "/"].includes(char)) {
|
|
if (numStr.length > 0) {
|
|
stack2.push(numStr);
|
|
numStr = "";
|
|
}
|
|
const topOperator = stack1.peek();
|
|
warOperator(char, topOperator);
|
|
} else if (["(", ")"].includes(char)) {
|
|
if (numStr.length > 0) {
|
|
stack2.push(numStr);
|
|
numStr = "";
|
|
}
|
|
if (char === "(") {
|
|
stack1.push(char);
|
|
} else {
|
|
while (stack1.length()) {
|
|
let operator = stack1.pop();
|
|
if (operator === "(") {
|
|
break;
|
|
}
|
|
stack2.push(operator);
|
|
}
|
|
}
|
|
} else {
|
|
numStr += char;
|
|
if (i === dealInfixExpression.length - 1) {
|
|
stack2.push(numStr);
|
|
}
|
|
}
|
|
}
|
|
|
|
while (stack1.length()) {
|
|
stack2.push(stack1.pop());
|
|
}
|
|
|
|
const postfixExpression = [];
|
|
while (stack2.length()) {
|
|
postfixExpression.push(stack2.pop());
|
|
}
|
|
postfixExpression.reverse();
|
|
return postfixExpression;
|
|
}
|
|
|
|
function calc(num1, num2, operator) {
|
|
const n1 = Number(num1);
|
|
const n2 = Number(num2);
|
|
let result;
|
|
switch (operator) {
|
|
case "+":
|
|
result = n1 + n2;
|
|
break;
|
|
case "-":
|
|
result = n1 - n2;
|
|
break;
|
|
case "x":
|
|
result = n1 * n2;
|
|
break;
|
|
case "/":
|
|
result = n1 / n2;
|
|
break;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function calculate(postfixExpression) {
|
|
const stack = new Stack();
|
|
for (let i = 0; i < postfixExpression.length; i++) {
|
|
const element = postfixExpression[i];
|
|
if (["+", "-", "x", "/"].includes(element)) {
|
|
const num2 = stack.pop();
|
|
const num1 = stack.pop();
|
|
stack.push(calc(num1, num2, element));
|
|
} else {
|
|
stack.push(element);
|
|
}
|
|
}
|
|
|
|
return stack.pop();
|
|
}
|
|
|
|
const expression = "12+((2.1+3) x45.2)-5.22";
|
|
const postfixExpression = infixToPostfix(expression);
|
|
console.log(postfixExpression);
|
|
const result = calculate(postfixExpression);
|
|
console.log(result);
|