2022-09-06 15:07:12 +02:00
|
|
|
import { Terminal } from "../../Terminal";
|
2021-09-16 01:50:44 +02:00
|
|
|
|
2022-09-06 15:07:12 +02:00
|
|
|
export function expr(args: (string | number | boolean)[]): void {
|
2021-09-16 01:50:44 +02:00
|
|
|
if (args.length === 0) {
|
2022-09-06 15:07:12 +02:00
|
|
|
Terminal.error("Incorrect usage of expr command. Usage: expr [math expression]");
|
2021-09-16 01:50:44 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
const expr = args.join("");
|
|
|
|
|
|
|
|
// Sanitize the math expression
|
2022-03-09 02:02:54 +01:00
|
|
|
const sanitizedExpr = expr.replace(/s+/g, "").replace(/[^-()\d/*+.%]/g, "");
|
2021-09-16 01:50:44 +02:00
|
|
|
let result;
|
|
|
|
try {
|
|
|
|
result = eval(sanitizedExpr);
|
|
|
|
} catch (e) {
|
2022-09-06 15:07:12 +02:00
|
|
|
Terminal.error(`Could not evaluate expression: ${sanitizedExpr}`);
|
2021-09-16 01:50:44 +02:00
|
|
|
return;
|
|
|
|
}
|
2022-09-06 15:07:12 +02:00
|
|
|
Terminal.print(result);
|
2021-09-16 01:50:44 +02:00
|
|
|
}
|