A library to evaluate logical expressions.
This library facilitates the work with logical (boolean) expressions. It allows you to tokenize and evaluate any logical expression. It supports the use of parentheses. |
---|
Install the @zk-kit/logical-expressions
package with npm:
npm i @zk-kit/logical-expressions
or yarn:
yarn add @zk-kit/logical-expressions
You can also load it using a script
tag using unpkg:
<script src="https://unpkg.com/@zk-kit/logical-expressions"></script>
or JSDelivr:
<script src="https://cdn.jsdelivr.net/npm/@zk-kit/logical-expressions"></script>
Supported logical operators: and
, or
, not
, xor
.
All other existing logical operators (nand
, nor
, xnor
) can be generated using the supported logical operators.
# tokenize(): string[]
Tokenizes a logical (boolean) expression. Splits the expression into meaningful tokens.
import { tokenize } from "@zk-kit/logical-expressions"
const expression = "true and false or ( true and true )"
const tokens = tokenize(expression)
console.log(tokens)
// Output: ["true", "and", "false", "or", "(", "true", "and", "true", ")"]
# precedence(): number
Returns the precedence of a logical operator. If the operator is not supported, the precedence will be 0.
import { precedence } from "@zk-kit/logical-expressions"
const result = precedence("and")
console.log(result) // Output: 1
# applyOperator(): boolean
Applies unary or binary operators to boolean values.
import { applyOperator } from "@zk-kit/logical-expressions"
// Unary operator
const result1 = applyOperator("not", true)
console.log(result1) // Output: false
// Binary operator
const result2 = applyOperator("and", true, false)
console.log(result2) // Output: false
# evaluate(): boolean
Evaluates a tokenized logical (boolean) expression.
There is no need to verify the correctness of the logical expression before calling the evaluate function, as this will be checked during the evaluation. If the expression is incorrect, an error will be thrown automatically.
Example of correct logical expression: "true and false"
.
Example of incorrect logical expression: "true true and false"
.
import { evaluate } from "@zk-kit/logical-expressions"
const expression = ["true", "and", "false"]
const result = evaluate(expression)
console.log(result) // Output: false