чат жпт вміє в корявий жс:
function evaluateExpression(expression) {
// Define the mathematical operations
const operations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b,
};
// Replace function names with JavaScript syntax
const sanitizedExpression = expression.replace(
/(add|subtract|multiply|divide)\(/g,
(_, fn) => `operations.${fn}(` // Replace with operations object reference
);
// Evaluate the sanitized expression
try {
const result = eval(sanitizedExpression); // Caution: eval can be unsafe
return result;
} catch (error) {
throw new Error(`Invalid expression: ${error.message}`);
}
}
// Example usage
const input = "multiply(add(subtract(5, multiply(7, 4)), divide(30, 7)), 7)";
console.log(evaluateExpression(input)); // Outputs the evaluated result