plugins-evert/utility/math.ts

30 lines
541 B
TypeScript
Raw Normal View History

2020-12-06 13:41:18 +00:00
import { evaluate } from 'mathjs';
2020-12-03 19:27:14 +00:00
function done(data: string): void {
if (process && process.send) {
process.send(data);
}
}
process.once('message', (msg: string) => {
2020-12-06 13:41:18 +00:00
let expr = msg.toString();
2020-12-03 19:27:14 +00:00
if (!expr) {
return done('null');
}
if (expr.indexOf('=') === expr.length - 1) {
expr = expr.substring(0, expr.length - 1);
}
expr = expr.replace(/π/g, 'pi');
let result = 'null';
try {
2020-12-06 13:41:18 +00:00
result = evaluate(expr);
} catch (e: any) {
2020-12-03 19:27:14 +00:00
return done(e.message);
}
return done(result.toString());
});