From 36e5b7bd5534f6bc87a7847dac72bc5d0d04c195 Mon Sep 17 00:00:00 2001 From: axetroy Date: Mon, 5 Mar 2018 03:33:30 +0800 Subject: [PATCH] feat: suppor logicExpression --- src/evaluate.ts | 6 ++++ test/LogicalExpression.test.ts | 56 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 test/LogicalExpression.test.ts diff --git a/src/evaluate.ts b/src/evaluate.ts index d70b9764..8d6c281a 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -459,6 +459,12 @@ const evaluate_map = { "^=": v => ($var.$set($var.$get() ^ v), $var.$get()), "&=": v => ($var.$set($var.$get() & v), $var.$get()) }[node.operator](evaluate(node.right, scope)); + }, + LogicalExpression(node: types.LogicalExpression, scope: Scope) { + return { + "||": () => evaluate(node.left, scope) || evaluate(node.right, scope), + "&&": () => evaluate(node.left, scope) && evaluate(node.right, scope) + }[node.operator](); } }; diff --git a/test/LogicalExpression.test.ts b/test/LogicalExpression.test.ts new file mode 100644 index 00000000..f9b4ee18 --- /dev/null +++ b/test/LogicalExpression.test.ts @@ -0,0 +1,56 @@ +import test from "ava"; +import * as fs from "fs"; + +import vm from "../src/vm"; + +test("LogicalExpression-or-1", t => { + const sandbox: any = vm.createContext({}); + + const num: any = vm.runInContext( + ` +module.exports = 0 || 2; + `, + sandbox + ); + + t.deepEqual(num, 2); +}); + +test("LogicalExpression-or-2", t => { + const sandbox: any = vm.createContext({}); + + const num: any = vm.runInContext( + ` +module.exports = 1 || 2; + `, + sandbox + ); + + t.deepEqual(num, 1); +}); + +test("LogicalExpression-and-1", t => { + const sandbox: any = vm.createContext({}); + + const num: any = vm.runInContext( + ` +module.exports = 1 && 2; + `, + sandbox + ); + + t.deepEqual(num, 2); +}); + +test("LogicalExpression-and-2", t => { + const sandbox: any = vm.createContext({}); + + const num: any = vm.runInContext( + ` +module.exports = 0 && 2; + `, + sandbox + ); + + t.deepEqual(num, 0); +});