UNPKG

@pawel-up/jexl

Version:

Javascript Expression Language: Powerful context-based expression parser and evaluator

83 lines 2.42 kB
import Evaluator from './evaluator/Evaluator.js'; import Lexer from './Lexer.js'; import Parser from './parser/Parser.js'; export default class Expression { _grammar; _exprStr; _ast; constructor(grammar, exprStr) { this._grammar = grammar; this._exprStr = exprStr; this._ast = null; } compile() { const lexer = new Lexer(this._grammar); const parser = new Parser(this._grammar); parser.addTokens(lexer.tokenize(this._exprStr)); this._ast = parser.complete(); return this; } eval(context = {}) { return this._eval(context); } async evalAsString(context = {}) { const result = await this.eval(context); if (result === null) { return 'null'; } if (result === undefined) { return 'undefined'; } return String(result); } async evalAsNumber(context = {}) { const result = await this.eval(context); if (result === null || result === undefined) { return NaN; } return Number(result); } async evalAsBoolean(context = {}) { const result = await this.eval(context); return !!result; } async evalAsArray(context = {}) { const result = await this.eval(context); if (result === null || result === undefined) { return []; } if (Array.isArray(result)) { return result; } return [result]; } async evalAsEnum(context = {}, allowedValues) { const result = await this.eval(context); if (allowedValues.includes(result)) { return result; } return undefined; } async evalWithDefault(context = {}, defaultValue) { const result = await this.eval(context); if (result === null || result === undefined) { return defaultValue; } return result; } async _eval(context) { const ast = this._getAst(); if (!ast) { throw new Error('No AST available for evaluation. Expression may not be compiled.'); } const evaluator = new Evaluator(this._grammar, context, context); return evaluator.eval(ast); } _getAst() { if (!this._ast) { this.compile(); } return this._ast; } } //# sourceMappingURL=Expression.js.map