mcalc/workers/compute.js

115 lines
2.8 KiB
JavaScript

/*
Copyright (C) 2025 filifa
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
importScripts("./lexer.js", "parser.js", "./math.js")
addEventListener("message", (message) => {
if (message.data.command === "compute") {
const expr = message.data.expr;
const modulus = BigInt(message.data.modulus);
const result = evaluate(expr, modulus);
postMessage(result);
}
});
function evaluate(expr, m) {
if (m <= 0n) {
throw new Error("invalid modulus");
}
const tokens = tokenize(expr);
console.log(tokens);
const queue = shunt(tokens);
console.log(queue);
const result = compute(queue, m);
return result;
}
function binaryOpPop(stack) {
const b = stack.pop();
const a = stack.pop();
if (a === undefined || b === undefined) {
throw new Error("invalid expression");
}
return [a, b];
}
function compute(queue, modulus) {
const stack = [];
for (const token of queue) {
if (typeof token === "bigint") {
stack.push(token);
} else if (token === "+") {
let [a, b] = binaryOpPop(stack);
a %= modulus;
b %= modulus;
const c = (a + b) % modulus;
stack.push(c);
} else if (token === "-") {
let [a, b] = binaryOpPop(stack);
a %= modulus;
b %= modulus;
const c = (a - b) % modulus;
stack.push(c);
} else if (token === "*") {
let [a, b] = binaryOpPop(stack);
a %= modulus;
b %= modulus;
const c = (a * b) % modulus;
stack.push(c);
} else if (token === "/") {
let [a, b] = binaryOpPop(stack);
a %= modulus;
b %= modulus;
const binv = modinv(b, modulus);
const c = (a * binv) % modulus;
stack.push(c);
} else if (token === "u") {
let a = stack.pop();
if (a === undefined) {
throw new Error("invalid expression");
}
a *= -1n;
stack.push(a);
} else if (token === "^") {
const [a, b] = binaryOpPop(stack);
const c = modpow(a, b, modulus);
stack.push(c);
} else if (token === "sqrt") {
const a = stack.pop();
const s = modsqrt(a, modulus);
stack.push(s);
} else if (token === "ord") {
const a = stack.pop();
const r = ord(a, modulus);
stack.push(r);
}
}
if (stack.length !== 1) {
throw new Error("error evaluating expression");
}
let result = stack[0] % modulus;
if (result < 0n) {
result += modulus;
}
return result;
}