Skip to content

Commit 10c3697

Browse files
committed
Implementing tools to work on sets
1 parent ab2809d commit 10c3697

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

logic.js

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -167,17 +167,17 @@ http://ricostacruz.com/cheatsheets/umdjs.html
167167

168168
jsonLogic.is_logic = function(logic) {
169169
return (
170-
logic !== null && typeof logic === "object" && ! Array.isArray(logic)
170+
typeof logic === "object" && // An object
171+
logic !== null && // but not null
172+
! Array.isArray(logic) && // and not an array
173+
Object.keys(logic).length === 1 // with exactly one key
171174
);
172175
};
173176

174177
/*
175178
This helper will defer to the JsonLogic spec as a tie-breaker when different language interpreters define different behavior for the truthiness of primitives. E.g., PHP considers empty arrays to be falsy, but Javascript considers them to be truthy. JsonLogic, as an ecosystem, needs one consistent answer.
176179
177-
Literal | JS | PHP | JsonLogic
178-
--------+-------+-------+---------------
179-
[] | true | false | false
180-
"0" | true | false | true
180+
Spec and rationale here: http://jsonlogic.com/truthy
181181
*/
182182
jsonLogic.truthy = function(value) {
183183
if(Array.isArray(value) && value.length === 0) {
@@ -257,9 +257,39 @@ http://ricostacruz.com/cheatsheets/umdjs.html
257257
}
258258
}
259259
return current; // Last
260+
}else if(op === "all") {
261+
var scopedData = jsonLogic.apply(values[0], data);
262+
var scopedLogic = values[1];
263+
// All of an empty set is false. Note, some and none have correct fallback after the for loop
264+
if( ! scopedData.length) {
265+
return false;
266+
}
267+
for(i=0; i < scopedData.length; i+=1) {
268+
if( ! jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {
269+
return false; // First falsy, short circuit
270+
}
271+
}
272+
return true; // All were truthy
273+
}else if(op === "none") {
274+
var scopedData = jsonLogic.apply(values[0], data);
275+
var scopedLogic = values[1];
276+
for(i=0; i < scopedData.length; i+=1) {
277+
if(jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {
278+
return false; // First truthy, short circuit
279+
}
280+
}
281+
return true; // All were falsy
282+
}else if(op === "some") {
283+
var scopedData = jsonLogic.apply(values[0], data);
284+
var scopedLogic = values[1];
285+
for(i=0; i < scopedData.length; i+=1) {
286+
if(jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {
287+
return true; // First truthy, short circuit
288+
}
289+
}
290+
return false; // None were truthy
260291
}
261292

262-
263293
// Everyone else gets immediate depth-first recursion
264294
values = values.map(function(val) {
265295
return jsonLogic.apply(val, data);

0 commit comments

Comments
 (0)