Skip to content

Instantly share code, notes, and snippets.

@fracarma
Created December 20, 2016 15:20
Show Gist options
  • Save fracarma/02bd705b1b315da6647a080a470a6f44 to your computer and use it in GitHub Desktop.
Save fracarma/02bd705b1b315da6647a080a470a6f44 to your computer and use it in GitHub Desktop.
JSON logical expression parser
condition = ["OR", ["AND",{field : 'field1', value : 'value2'},{field : 'field2', value : 'value2'}], {field : 'field2', value : 'value1'}];
item = {obj:{'field1' : 'value1','field2' : 'value2'}};
console.log(validateCondition(condition,item));
function validateCondition(condition, item){
if(!Array.isArray(condition)){
return assertEquals(condition,item);
}
var res = false;
var logicalOperator = condition[0];
for (var i = 1; i < condition.length; i++) {
var loopRes = validateCondition(condition[i], item);
if(logicalOperator === 'AND'){
res = (i != 1) ? loopRes && res : loopRes;
}
if(logicalOperator === 'OR'){
res = (i != 1) ? loopRes || res : loopRes;
}
}
return res;
}
//fieldAndValueObj = {field : 'fieldName' , value : 'expectedValue'}
function assertEquals(fieldAndValueObj, item){
var field = fieldAndValueObj.field;
var expectedValue = fieldAndValueObj.value;
if(!(field in item.obj)){
throw "The field "+field+" is not in the item";
}
var realValue = item.obj[field];
return expectedValue === realValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment