public decimal Solve(Equation equation) { decimal left = 0m; decimal right = 0m; for (var i = 0; i < equation.Tokens.Count; i++) { var token = equation.Tokens[i]; if (i == 0 && token.Type == TokenType.Value) { left = (decimal)token.Value; continue; } if (token.Type == TokenType.Operator) { var rightToken = equation.Tokens[++i]; if (rightToken.Type == TokenType.Value) { right = (decimal)rightToken.Value; } left = Solve(left, right, token.Value.ToString()); } } return left; }
public Equation Parse(string value) { var equation = new Equation() { Tokens = new List<Token>() }; if (value == null) return equation; var current = ""; var currentType = TokenType.None; Token currentToken = null; for (int i = 0; i < value.Length; i++) { var item = value[i]; var type = GetTokenType(item); if (type != currentType) { // add if (currentToken != null) { if (currentToken.Type == TokenType.Value) { currentToken.Value = decimal.Parse(current); } else { currentToken.Value = current; } equation.Tokens.Add(currentToken); } currentToken = new Token(); currentToken.Type = type; current = item.ToString(); } else { current += item; } } if (currentToken != null) { if (currentToken.Type == TokenType.Value) { currentToken.Value = decimal.Parse(current); } else { currentToken.Value = current; } equation.Tokens.Add(currentToken); } return equation; }
public void WhenExecutingAndAddEquation_ThenResultShouldEqualThree() { // Arrange var calculator = new Calculator(); var equation = new Equation() { Tokens = new List<Token>() { new Token() {Value = 1m, Type = TokenType.Value}, new Token() {Value = "+", Type = TokenType.Operator}, new Token() {Value = 2m, Type = TokenType.Value}, } }; // Act var result = calculator.Solve(equation); // Assert Assert.AreEqual(3m, result); }