Update AdvancedMath.js

This commit is contained in:
pa1va
2026-03-10 01:15:05 -03:00
committed by GitHub
parent 7bb88e6919
commit f4f75cbd22
+15 -9
View File
@@ -26,8 +26,18 @@ var constants = {
// Safe evaluation function that handles advanced math
function evaluate(expression) {
try {
// Replace mathematical constants
var processed = expression
// Fixes decimal arithmetic
var cleanExpr = expression.replace(/\s+/g, '').toLowerCase();
// Allows numbers (including decimals), basic operators, and explicitly permitted math terms only
var safeRegex = /^(\d*\.?\d+|[+\-*/()^%,]|sin|cos|tan|asin|acos|atan|atan2|sinh|cosh|tanh|asinh|acosh|atanh|log|ln|exp|pow|sqrt|cbrt|abs|floor|ceil|round|trunc|min|max|random|pi|e|sind|cosd|tand)+$/;
if (!safeRegex.test(cleanExpr)) {
throw new Error("Invalid characters or unauthorized functions in expression");
}
// Replace mathematical constants (Original Structure)
var processed = cleanExpr
.replace(/\bpi\b/gi, Math.PI)
.replace(/\be\b/gi, Math.E);
@@ -83,13 +93,9 @@ function evaluate(expression) {
// Handle ^ for exponentiation: convert 2^3 to Math.pow(2,3)
processed = processed.replace(/([\d.]+|\))\^([\d.]+|\([^)]*\))/g, 'Math.pow($1,$2)');
// Sanitize expression (only allow safe characters)
if (!/^[0-9+\-*/().\s\w,]+$/.test(processed)) {
throw new Error("Invalid characters in expression");
}
// Evaluate the processed expression
var result = eval(processed);
// Replacing eval() with a scoped function constructor
// This is safe because the strict whitelist guarantees only math reaches this point
var result = new Function('return ' + processed)();
if (!isFinite(result) || isNaN(result)) {
throw new Error("Invalid result");