mcalc/modules/parser.js

70 lines
1.3 KiB
JavaScript

function isLeftAssociative(op) {
return op === "+" || op === "-" || op === "*" || op === "/";
}
function popOps(opstack, queue, op) {
const prec = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
while (true) {
const op2 = opstack.at(-1);
if (op2 === undefined) {
break;
} else if (op2 === "(") {
break;
}
if ((prec[op2] > prec[op]) || (prec[op2] === prec[op] && isLeftAssociative(op))) {
opstack.pop();
queue.push(op2);
} else {
break;
}
}
opstack.push(op);
}
function popBetweenParens(opstack, queue) {
while (opstack.at(-1) !== "(") {
if (opstack.length === 0) {
throw new Error("mismatched parentheses");
}
const op = opstack.pop();
queue.push(op);
}
opstack.pop();
}
function empty(opstack, queue) {
while (opstack.length !== 0) {
const op = opstack.pop();
if (op === "(") {
throw new Error("mismatched parentheses");
}
queue.push(op);
}
}
function shunt(tokens) {
const queue = [];
const opstack = [];
for (const token of tokens) {
if (typeof token === "bigint") {
queue.push(token);
} else if (/[-+*/^]/.test(token)) {
popOps(opstack, queue, token);
} else if (token === "(") {
opstack.push(token);
} else if (token === ")") {
popBetweenParens(opstack, queue);
}
}
empty(opstack, queue);
return queue;
}
export { shunt };