From 9f6f7768d4ea505b8504f0d1b5ac66974f6d0905 Mon Sep 17 00:00:00 2001 From: Jeremy Wadhams Date: Thu, 27 Oct 2016 16:51:44 -0500 Subject: [PATCH] New methods, esp existing libraries, may take one arg that is an array, that contains JsonLogic rules or 'var's --- logic.js | 4 ++++ tests/tests.js | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/logic.js b/logic.js index c2d4d3f..69cf4b0 100644 --- a/logic.js +++ b/logic.js @@ -160,6 +160,10 @@ jsonLogic.truthy = function(value){ }; jsonLogic.apply = function(logic, data){ + //Does this array contain logic? Only one way to find out. + if(Array.isArray(logic)){ + return logic.map(function(l){ return jsonLogic.apply(l,data); }); + } //You've recursed to a primitive, stop! if( ! jsonLogic.is_logic(logic) ){ return logic; diff --git a/tests/tests.js b/tests/tests.js index 94626f0..72fc050 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -112,6 +112,27 @@ QUnit.test( "Expanding functionality with add_operator", function( assert) { jsonLogic.add_operation("fives", fives); assert.equal( jsonLogic.apply({"fives.add" : 37}), 42 ); assert.equal( jsonLogic.apply({"fives.subtract" : [47] }), 42 ); + + //Calling a method with multiple var as arguments. + jsonLogic.add_operation("times", function(a,b){ return a*b; }); + assert.equal( + jsonLogic.apply( + {"times" : [{"var":"a"}, {"var":"b"}]}, + {a:6,b:7} + ), + 42 + ); + + //Calling a method that takes an array, but the inside of the array has rules, too + jsonLogic.add_operation("array_times", function(a){ return a[0]*a[1]; }); + assert.equal( + jsonLogic.apply( + {"array_times" : [[{"var":"a"}, {"var":"b"}]]}, + {a:6,b:7} + ), + 42 + ); + }); QUnit.test( "Expanding functionality with method", function( assert) { @@ -143,5 +164,4 @@ QUnit.test( "Expanding functionality with method", function( assert) { ); assert.equal(a.count, 42); //Happy state change - });