Skip to content

Commit

Permalink
Add throwing exception if variable is not decimal or boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
dimabarbul committed Feb 9, 2016
1 parent 94446dc commit 3f78299
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 4 deletions.
40 changes: 40 additions & 0 deletions Calculator.Core.Tests/CalculatorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,5 +255,45 @@ public void Calculate_UndefinedVariable_ThrowsException()
{
Calculator.Calculate("a");
}

[TestMethod]
[ExpectedExceptionWithCode(typeof(CalculateException), (int)CalculateExceptionCode.StringVariable)]
public void Calculate_StringVariable_ThrowsException()
{
Calculator.Calculate(
"a + c",
new Dictionary<string, object>()
{
{ "a", 1 },
{ "c", "test" }
}
);
}

[TestMethod]
[ExpectedExceptionWithCode(typeof(CalculateException), (int)CalculateExceptionCode.StringVariable)]
public void Calculate_OperationVariable_ThrowsException()
{
Calculator.Calculate(
"c / 0",
new Dictionary<string, object>()
{
{ "c", "-" }
}
);
}

[TestMethod]
[ExpectedExceptionWithCode(typeof(CalculateException), (int)CalculateExceptionCode.StringVariable)]
public void Calculate_SubformulaVariable_ThrowsException()
{
Calculator.Calculate(
"v",
new Dictionary<string, object>()
{
{ "v", "(1+2)" }
}
);
}
}
}
13 changes: 9 additions & 4 deletions Calculator.Core/Calculator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,15 @@ public static TResult Calculate<TResult>(string formula, Dictionary<string, obje
throw new CalculateException(CalculateExceptionCode.UnknownVariable);
}

operands.Push(new Token(
variables[token.Text].ToString(),
FormulaTokenizer.DetectTokenType(variables[token.Text])
));
TokenType variableType = FormulaTokenizer.DetectTokenType(variables[token.Text]);
if (!FormulaTokenizer.IsValueTokenType(variableType))
{
throw new CalculateException(CalculateExceptionCode.StringVariable);
}

Token variableToken = new Token(variables[token.Text].ToString(), variableType);

operands.Push(variableToken);
break;
default:
OperationBase operation = OperationFactory.Create(token, operands.Count == 0);
Expand Down
1 change: 1 addition & 0 deletions Calculator.Core/Enum/CalculateExceptionCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ internal enum CalculateExceptionCode
NotSingleResult = 2,
MissingOperand = 3,
UnknownVariable = 4,
StringVariable = 5,
}
}
5 changes: 5 additions & 0 deletions Calculator.Core/FormulaTokenizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,10 @@ public static TokenType DetectTokenType(object value)

return token.Type;
}

public static bool IsValueTokenType(TokenType type)
{
return type == TokenType.Bool || type == TokenType.Decimal;
}
}
}

0 comments on commit 3f78299

Please sign in to comment.