~james/gengo

gengo/samples-test/samples/JavaScript/count_expression.js -rw-r--r-- 869 bytes
50871857 — james chore(import): snapshot james.dad.town/gengo at 8f775550b0ee 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Parses and evaluates a mathematical expression string
 * @param {string} expression - The mathematical expression to evaluate
 * @returns {number} The result of the expression
 */
function parseExpression(expression) {
    try {
        // Remove whitespace and validate input
        const cleanExpression = expression.replace(/\s+/g, '');
        
        // Check for invalid characters
        if (/[^0-9+\-*/().]/.test(cleanExpression)) {
            throw new Error('Invalid characters in expression');
        }

        // Use Function constructor to safely evaluate the expression
        // This handles basic arithmetic operations: +, -, *, /
        return Function(`return ${cleanExpression}`)();
    } catch (error) {
        throw new Error('Invalid expression: ' + error.message);
    }
}

module.exports = parseExpression;