UNPKG

som-exp-sdk

Version:

Evaluate the User Expression

63 lines (62 loc) 2.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ExpressionEvaluator = void 0; const base_expression_1 = require("./base-expression"); const constants_1 = require("./constants"); const utils_1 = require("../util/utils"); const baseExpression = new base_expression_1.BaseExpression(); class ExpressionEvaluator { constructor() { this.evalExpr = (expression) => { let output = this.const.INVALID_EXPRESSION; try { if (!!expression) { const hasMathExpression = this.hasMathExpression(expression); const expressionType = this.utils.getExpressionClassInfo(expression); if (expressionType && expressionType.isHealthy()) { const fileName = expressionType.getFileName(); const className = expressionType.getClassName(); output = baseExpression.evaluateExpression(`(() => { const { ${className} } = require("./${fileName}"); return (new ${className}()).${expression}; })()`); } else if (hasMathExpression) { output = baseExpression.evaluateExpression("Math." + expression); } else { output = baseExpression.evaluateExpression(expression); } } } catch (e) { console.log(`Error occurred while evaluating the expression. Error is ${e}`); } return output; }; this.hasMathExpression = (expression) => { let output = false; if (!!expression) { const expressionArr = expression.split("("); const mathMethods = Object.getOwnPropertyNames(Math); if (expressionArr && Array.isArray(expressionArr) && expressionArr.length > 0 && mathMethods && Array.isArray(mathMethods) && mathMethods.length > 0) { const expressionMethodName = expressionArr[0]; for (let method = 0; method < mathMethods.length; ++method) { const includesMathMethod = (!!expressionMethodName && !!mathMethods[method] && mathMethods[method] === expressionMethodName); if (includesMathMethod) { output = true; break; } } } } return output; }; this.utils = new utils_1.Utils(); this.const = new constants_1.Constants(); } } exports.ExpressionEvaluator = ExpressionEvaluator;