-
Supports AND (&), OR (|), and NOT (!) operators.
-
Supports parenthesis grouping.
-
Supports input error handling.
The algorithm works as follows:
When evaluator.evaluate(expression: input) called, the expression is validated against the following criteria:
-
There are only allowed characters.
-
There are no unmatched parentheses.
-
The syntax of all unary and binary operators is valid.
If the validation fails, the corresponding exception is thrown.
Next, if the validation is successful, the following steps are repeated until the entire input string is transformed into a single value of "true" or "false":
-
Find the first sub-expression inside parentheses that does not have nested parentheses.
-
Evaluate the sub-expression:
2.1 Find all the unary operations, evaluate them, and replace them with the evaluated values. This leaves only the
ANDandORoperators in the sub-expression.2.2 Split the sub-expression into more sub-expressions by the
ORoperator, since theANDoperations must be evaluated before theORoperations.2.3 Evaluate and replace these
ANDoperation sub-expressions with the evaluated values. This leaves only theORoperators in the sub-expression.2.4 Evaluate the values of all
ORoperations in the resulting expression and replace the original expression inside the parentheses with its result -"true"or"false". -
Repeat the steps 1-2 until all parentheses in the input expression, and then the final expression, have been replaced with their evaluated values.
Thus, as a result, we get a single value of "true" or "false", which should be returned as the boolean result of the function.
((true & false) | !(true | !false))
(false | !(true | !false))
(false | !(true | true))
(false | !true)
(false | false)
false