Created
December 20, 2016 15:20
-
-
Save fracarma/02bd705b1b315da6647a080a470a6f44 to your computer and use it in GitHub Desktop.
JSON logical expression parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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