Beispiel #1
0
        public void PerformOperation_should_return_value_for_remainder_of_division()
        {
            _calculationOperation.AddOperation("%", (x, y) => x % y, OperationCategory.Multiplicative);

            var result = _calculationOperation.PerformOperation("%", 5, 4);

            Assert.AreEqual(1, result);
        }
        public double Execute(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(0);
            }
            Stack <string> stack = new Stack <string>();
            Queue <string> queue = new Queue <string>(_postfixNotationParseEquation.GetPostfixNotationEquation(input));
            string         str   = queue.Dequeue();

            while (queue.Count >= 0)
            {
                if (str.ToTryParseToDouble(out _))
                {
                    stack.Push(str);
                    str = queue.Count > 0 ? queue.Dequeue() : string.Empty;
                }
                else
                {
                    double summ = 0;
                    try
                    {
                        if (stack.Count == 1)
                        {
                            if (stack.Pop().ToTryParseToDouble(out var arg3))
                            {
                                summ = arg3;
                            }
                        }
                        else
                        {
                            bool res  = stack.Pop().ToTryParseToDouble(out var arg1);
                            bool res2 = stack.Pop().ToTryParseToDouble(out var arg2);

                            if (res && res2)
                            {
                                summ = _calculationOperation.PerformOperation(str, arg2, arg1);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    stack.Push(summ.ToString(CultureInfo.InvariantCulture));
                    if (queue.Count > 0)
                    {
                        str = queue.Dequeue();
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(stack.Pop().ConvertToDouble());
        }