Esempio n. 1
0
        public async Task IsExpressionVisitorResultEqualToCompiledExpression(string expression)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped <ICalculator, DirectCalculator>();
            var compiledResult = Expression.Lambda <Func <double> >(ExpressionTreeBuilder.Build(expression)).Compile()();
            var visitorResult  = await CalculatorExpression.Calculator.CalculateAsync(expression, serviceCollection);

            Assert.Equal(compiledResult, visitorResult);
        }
Esempio n. 2
0
        /// <summary>
        /// Evaluates the result value for the provided math expression.
        /// </summary>
        /// <param name="s">Input string (math expression in Infix notation).</param>
        /// <returns>Result of evaluation of the expression.</returns>
        public double Evaluate(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(s));
            }

            var builder = new ExpressionTreeBuilder();
            var expr    = builder.Build(s);

            var visitor = new MathExpressionVisitor();
            var result  = visitor.Visit(expr);

            return(result);
        }
Esempio n. 3
0
        public void CanBuildExpressionTree()
        {
            var input = new List <Token>()
            {
                new Token {
                    Type = TokenType.Number, Value = 5
                },
                new Token {
                    Type = TokenType.Add, Value = null
                },
                new Token {
                    Type = TokenType.Number, Value = 7
                },
            };

            var expectedOutput = new NodeAdd
            {
                Left = new NodeNumber {
                    Value = 5
                },
                Right = new NodeNumber {
                    Value = 7
                }
            };

            var root = ExpressionTreeBuilder.Build(input) as NodeAdd;

            Assert.NotNull(root);

            var left = root.Left as NodeNumber;

            Assert.NotNull(left);
            Assert.Equal(5, left.Value);

            var right = root.Right as NodeNumber;

            Assert.NotNull(right);
            Assert.Equal(7, right.Value);
        }