diff --git a/.eslintrc.json b/.eslintrc.json index 30a74a3..a662389 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -23,7 +23,8 @@ "@typescript-eslint/no-unused-vars": ["warn", {"argsIgnorePattern": "^_"}], "quotes": ["warn", "single"], "max-len": ["warn", {"code": 100, "tabWidth": 4, "ignoreUrls": true, "ignorePattern": "^import|^export"}], - "newline-per-chained-call": [2, {"ignoreChainWithDepth": 3}] + "newline-per-chained-call": [2, {"ignoreChainWithDepth": 3}], + "no-case-declarations": "off" }, "ignorePatterns": ["**/*.js"] } diff --git a/index.ts b/index.ts index d1f93f0..f4e1a97 100644 --- a/index.ts +++ b/index.ts @@ -150,12 +150,13 @@ function evaluate(_node: jsep.Expression, context: object) { return node.value; case 'LogicalExpression': - if (node.operator === '||') { - return evaluate(node.left, context) || evaluate(node.right, context); - } else if (node.operator === '&&') { - return evaluate(node.left, context) && evaluate(node.right, context); + const leftValue = evaluate(node.left, context); + if (node.operator === '||' && leftValue) { + return leftValue; + } else if (node.operator === '&&' && !leftValue) { + return leftValue; } - return binops[node.operator](evaluate(node.left, context), evaluate(node.right, context)); + return binops[node.operator](leftValue, evaluate(node.right, context)); case 'MemberExpression': return evaluateMember(node, context)[1]; @@ -222,15 +223,17 @@ async function evalAsync(_node: jsep.Expression, context: object) { case 'LogicalExpression': { if (node.operator === '||') { - return ( - (await evalAsync(node.left, context)) || - (await evalAsync(node.right, context)) - ); + const left = await evalAsync(node.left, context); + if (left) { + return left; + } + return await evalAsync(node.right, context); } else if (node.operator === '&&') { - return ( - (await evalAsync(node.left, context)) && - (await evalAsync(node.right, context)) - ); + const left = await evalAsync(node.left, context); + if (!left) { + return left; + } + return await evalAsync(node.right, context); } const [left, right] = await Promise.all([ diff --git a/test.js b/test.js index 93475e4..364fcc8 100644 --- a/test.js +++ b/test.js @@ -62,9 +62,9 @@ const fixtures = [ {expr: '1 >= 2', expected: false }, // logical expression lazy evaluation - {expr: 'true || false', expected: true }, + {expr: 'true || throw()', expected: true }, {expr: 'false || true', expected: true }, - {expr: 'false && true', expected: false }, + {expr: 'false && throw()', expected: false }, {expr: 'true && false', expected: false }, // member expression