Skip to content

Commit

Permalink
New methods, esp existing libraries, may take one arg that is an arra…
Browse files Browse the repository at this point in the history
…y, that contains JsonLogic rules or 'var's
  • Loading branch information
jwadhams committed Oct 27, 2016
1 parent 5809e64 commit 9f6f776
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions logic.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
22 changes: 21 additions & 1 deletion tests/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -143,5 +164,4 @@ QUnit.test( "Expanding functionality with method", function( assert) {
);
assert.equal(a.count, 42); //Happy state change


});

0 comments on commit 9f6f776

Please sign in to comment.