Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unaryOperatorsDictionary to manage custom operators that are both unaries and binaries better #160

Merged
merged 1 commit into from
Sep 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions CodingSeb.ExpressionEvaluator/ExpressionEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,12 @@ protected enum TryBlockEvaluatedState
ExpressionOperator.UnaryMinus
};

protected IDictionary<string, ExpressionOperator> unaryOperatorsDictionary = new Dictionary<string, ExpressionOperator>()
{
{ "+", ExpressionOperator.UnaryPlus },
{ "-", ExpressionOperator.UnaryMinus }
};

protected virtual IList<ExpressionOperator> LeftOperandOnlyOperatorsEvaluationDictionary => leftOperandOnlyOperatorsEvaluationDictionary;
protected virtual IList<ExpressionOperator> RightOperandOnlyOperatorsEvaluationDictionary => rightOperandOnlyOperatorsEvaluationDictionary;
protected virtual IList<IDictionary<ExpressionOperator, Func<dynamic, dynamic, object>>> OperatorsEvaluations => operatorsEvaluations;
Expand Down Expand Up @@ -2748,12 +2754,11 @@ protected virtual bool EvaluateOperators(string expression, Stack<object> stack,
{
string op = match.Value;

if (op.Equals("+") && (stack.Count == 0 || (stack.Peek() is ExpressionOperator previousOp && !LeftOperandOnlyOperatorsEvaluationDictionary.Contains(previousOp))))
stack.Push(ExpressionOperator.UnaryPlus);
else if (op.Equals("-") && (stack.Count == 0 || (stack.Peek() is ExpressionOperator previousOp2 && !LeftOperandOnlyOperatorsEvaluationDictionary.Contains(previousOp2))))
stack.Push(ExpressionOperator.UnaryMinus);
if (unaryOperatorsDictionary.ContainsKey(op) && (stack.Count == 0 || (stack.Peek() is ExpressionOperator previousOp && !LeftOperandOnlyOperatorsEvaluationDictionary.Contains(previousOp))))
stack.Push(unaryOperatorsDictionary[op]);
else
stack.Push(operatorsDictionary[op]);

i += op.Length - 1;
return true;
}
Expand Down