UNPKG

numenor

Version:

Customizable, safe evaluator of JavaScript-like expressions.

76 lines (62 loc) 2.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Conditional = void 0; var _ = require("./"); var _Parser = require("../../Parser"); var _Error = require("../Error"); var Conditional = function Conditional(expr, options, compile) { if (expr.type !== _Parser.ExpressionType.Conditional) { throw new TypeError((0, _Error.UnknownExpression)(expr)); } var lhs = compile(expr.lhs, options, compile); var thenBranch = compile(expr.thenBranch, options, compile); var elseBranch = compile(expr.elseBranch, options, compile); var isLHSAsync = (0, _.hasAsyncValue)(lhs); var isThenAsync = (0, _.hasAsyncValue)(thenBranch); var isElseAsync = (0, _.hasAsyncValue)(elseBranch); var isAsync = isLHSAsync || isThenAsync || isElseAsync; var isLHSConst = (0, _.hasConstValue)(lhs); var isThenConst = (0, _.hasConstValue)(thenBranch); var isElseConst = (0, _.hasConstValue)(elseBranch); var isConst = isLHSConst && isThenConst && isElseConst; if (isAsync) { if (isLHSAsync) { return (0, _.mark)({ isAsync: isAsync, isConst: isConst }, function (context, stack) { return lhs(context, stack).then(function (thruthy) { return thruthy ? thenBranch(context, stack) : elseBranch(context, stack); }); }); } if (isLHSConst) { return (0, _.evalConst)(lhs) ? (0, _.mark)({ isAsync: isThenAsync, isConst: isThenConst }, thenBranch) : (0, _.mark)({ isAsync: isElseAsync, isConst: isElseConst }, elseBranch); } return (0, _.mark)({ isAsync: isAsync }, function (context, stack) { if (lhs(context, stack)) { var _value = thenBranch(context, stack); return isThenAsync ? _value : Promise.resolve(_value); } var value = elseBranch(context, stack); return isElseAsync ? value : Promise.resolve(value); }); } if (isLHSConst) { return (0, _.evalConst)(lhs) ? thenBranch : elseBranch; } return function (context, stack) { return lhs(context, stack) ? thenBranch(context, stack) : elseBranch(context, stack); }; }; exports.Conditional = Conditional;