Exemplo n.º 1
0
 public Operation(MathValue a, MathValue b, OperationType type) : base()
 {
     A      = a;
     B      = b;
     OpType = type;
 }
Exemplo n.º 2
0
 public Operation(MathValue a, MathValue b) : this(a, b, OperationType.Sum)
 {
 }
Exemplo n.º 3
0
        private MathValue GetValueFromToken(Token[] tokens, ref int currentTokenIndex, int currentOperationPriority = 0)
        {
            Token     current = tokens[currentTokenIndex];
            MathValue currentTokenAsMathValue;

            if (current.Type == TokenType.OpenParenthesis)
            {
                int          openedParenthesis       = 1;
                List <Token> tokensInsideParenthesis = new List <Token>();

                int j;
                for (j = currentTokenIndex + 1; j < tokens.Length; j++)
                {
                    Token innerToken = tokens[j];
                    if (innerToken.Type == TokenType.OpenParenthesis)
                    {
                        openedParenthesis++;
                    }
                    else if (innerToken.Type == TokenType.CloseParenthesis)
                    {
                        openedParenthesis--;
                    }
                    if (openedParenthesis == 0)
                    {
                        break;
                    }

                    tokensInsideParenthesis.Add(innerToken);
                }

                currentTokenAsMathValue = ParseNext(tokensInsideParenthesis.ToArray(), 0);

                currentTokenIndex = j;
            }
            else
            {
                currentTokenAsMathValue = new MathValue(current.ToDecimalNumber());
            }
            if (currentTokenIndex >= tokens.Length - 1)
            {
                return(currentTokenAsMathValue);
            }
            else
            {
                // Speculate if next operation is a higher priority
                // As number is received, next SHOULD be an operator

                Token         nextOperator  = tokens[currentTokenIndex + 1];
                OperationType operationType = OperatorUtils.GetOperatorTypeFromTokenType(nextOperator.Type);
                int           nextPriority  = OperatorUtils.GetPriority(operationType);

                if (nextPriority > currentOperationPriority)
                {
                    // So, next operation will be evaluated as a single value
                    currentTokenIndex += 2;
                    return(new Operation(currentTokenAsMathValue, GetValueFromToken(
                                             tokens,
                                             ref currentTokenIndex,
                                             nextPriority
                                             ), operationType));
                }

                return(currentTokenAsMathValue);
            }
        }