UNPKG

@schoenbergerb/logical-expression-parser

Version:

Logical expression parser and evaluates result, suitable for permissions management

57 lines (40 loc) 1.51 kB
# Logical Expression Parser <br /> This is a logical expression parser for TypeScript, it can parse a logical expression into a AST object and evaluates the result using your token checking function. It's original developed by NimitzDEV: https://github.com/NimitzDEV/logical-expression-parser <br /> ### Improvements compared to the original: - typescript support - custom logical operators <br /> #### [Default] logical operators - `/` Or - `&` And - `!` Not - `()` Parentheses <br /> ## How it works 1. The parser parse and tokenize the expression, for example one of your function requires `REGISTERED&(SPECIAL/INVITED)` 1. Parser then will pass `REGISTERED`, `SPECIAL` and `INVITED` into your token checking function to get a boolean result 1. Finaly the parser will evaluates the final result <br /> <br /> ## Examples ```typescript const { evaluate } = ExpressionParserFactory.init().build(); const result1 = evaluate("REGISTERED&(SPECIAL/INVITED)", ["REGISTERED", "INVITED"]); // --> true const result2 = evaluate("REGISTERED&(SPECIAL/INVITED)", ["REGISTERED"]); // --> false ``` <br /> use custom operators if needed: ```typescript const { evaluate } = ExpressionParserFactory.init() .setToken(Token.OPERATOR_AND, '+') .setToken(Token.OPERATOR_NOT, '-') .setToken(Token.OPERATOR_OR, '|') .setToken(Token.PARENTHESES_OPEN, '{') .setToken(Token.PARENTHESES_CLOSE, '}') .build(); const result = evaluator.evaluate("{A+C}|{B&-C}", ['A', 'B']) ```