-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryOpNode.cs
More file actions
49 lines (48 loc) · 2.06 KB
/
BinaryOpNode.cs
File metadata and controls
49 lines (48 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
namespace ExpressionParser
{
// A binary operator node. Supports +, -, *, and /.
public class BinaryOpNode : ExpressionNode
{
private ExpressionNode _left;
private ExpressionNode _right;
private TokenType _operator;
public BinaryOpNode(ExpressionNode left, TokenType op, ExpressionNode right)
{
_left = left;
_operator = op;
_right = right;
}
public override object Evaluate(Dictionary<string, object> variables)
{
object leftVal = _left.Evaluate(variables);
object rightVal = _right.Evaluate(variables);
switch (_operator)
{
case TokenType.Plus:
if (Parser.IsNumeric(leftVal) && Parser.IsNumeric(rightVal))
return Convert.ToDouble(leftVal) + Convert.ToDouble(rightVal);
throw new Exception("The '+' operator requires both operands to be numeric.");
case TokenType.Minus:
if (Parser.IsNumeric(leftVal) && Parser.IsNumeric(rightVal))
return Convert.ToDouble(leftVal) - Convert.ToDouble(rightVal);
throw new Exception("The '-' operator requires both operands to be numeric.");
case TokenType.Multiply:
if (Parser.IsNumeric(leftVal) && Parser.IsNumeric(rightVal))
return Convert.ToDouble(leftVal) * Convert.ToDouble(rightVal);
throw new Exception("The '*' operator requires both operands to be numeric.");
case TokenType.Divide:
if (Parser.IsNumeric(leftVal) && Parser.IsNumeric(rightVal))
{
double denominator = Convert.ToDouble(rightVal);
if (denominator == 0)
throw new Exception("Division by zero.");
return Convert.ToDouble(leftVal) / denominator;
}
throw new Exception("The '/' operator requires both operands to be numeric.");
default:
throw new Exception($"Unsupported binary operator: {_operator}");
}
}
}
}