Commit 89a3e61
committed
feat(calculator): Add mathematical expression evaluator
Adds a comprehensive engine for parsing and evaluating mathematical expressions from strings.
Includes core components:
- Tokenizer (`tokenizeCore`): Performs lexical analysis to break the expression into numbers, operators, identifiers, etc. Handles unary minus detection.
- Shunting-Yard (`shuntingYardCore`): Implements the algorithm to convert infix token streams to Reverse Polish Notation (RPN), respecting operator precedence and associativity.
- RPN Evaluator (`evaluateRPNCore`): Calculates the result from the RPN queue, handling stack operations, function calls, and basic arithmetic/comparison logic.
Features:
- Support for standard arithmetic (+, -, *, /, %, ^), comparisons (>, <, >=, <=, ==, !=), unary minus, parentheses, function calls (requires predefined `functions` map), and constants (requires predefined `constants` map).
- Recursive handling of ternary operators (`condition ? trueExpr : falseExpr`) via `parseTernary` and the main `calculate` function, enabling short-circuit evaluation.
- Optional unwrapping of redundant outer parentheses in the main `calculate` function.
- Graceful error handling: Issues `console.warn` for syntax issues, unknown identifiers, mismatched parentheses, stack underflows, division/modulo by zero, etc., and returns `null` upon failure instead of throwing hard errors.
- Comments have been refined to explain complex logic ('why') rather than just restating the code ('what'), improving clarity where needed without being overly verbose.1 parent 4d6f6b6 commit 89a3e61
1 file changed
+833
-68
lines changed
0 commit comments