Created
November 2, 2012 08:45
-
-
Save tikurahul/3999552 to your computer and use it in GitHub Desktop.
A simple expression evaluator, inspired by MongoDB.
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
// a simple expression evaluator | |
/* | |
{ | |
"or": [ | |
{"ne": ['foo', 'bar']} | |
] | |
} | |
*/ | |
function evaluate(expression) { | |
var ALL_PREDICATES = {}, | |
SIMPLE_PREDICATES = {}, | |
subPredicates = null, | |
key = null, | |
value = null, | |
i = 0; | |
// define all predicates | |
var lt = function (a, b) { | |
return a < b ? true : false; | |
}; | |
var gt = function (a, b) { | |
return a > b ? true : false; | |
}; | |
var lte = function (a, b) { | |
return a <= b ? true : false; | |
}; | |
var gte = function (a, b) { | |
return a >= b ? true : false; | |
}; | |
var ne = function (a, b) { | |
return a != b ? true : false; | |
}; | |
var eq = function (a, b) { | |
return a === b ? true : false; | |
}; | |
var regex = function (pattern, a) { | |
return new RegExp(pattern).test(a); | |
}; | |
SIMPLE_PREDICATES.lt = lt; | |
SIMPLE_PREDICATES.gt = gt; | |
SIMPLE_PREDICATES.lte = lte; | |
SIMPLE_PREDICATES.gte = gte; | |
SIMPLE_PREDICATES.ne = ne; | |
SIMPLE_PREDICATES.eq = eq; | |
SIMPLE_PREDICATES.regex = regex; | |
var evaluateSimplePredicate = function (predicate) { | |
var property = null; | |
if (typeof(predicate) === 'object') { | |
for (property in predicate) { | |
if (predicate.hasOwnProperty(property) && SIMPLE_PREDICATES[property]) { | |
return SIMPLE_PREDICATES[property].apply(null, predicate[property]); | |
} | |
} | |
} | |
}; | |
for (key in expression) { | |
if (expression.hasOwnProperty(key)) { | |
// simple predicate ? | |
if (SIMPLE_PREDICATES[key]) { | |
return evaluateSimplePredicate(expression); | |
} | |
if (key === 'or') { | |
subPredicates = expression[key] || []; | |
for (i = 0; i < subPredicates.length; i += 1) { | |
if (evaluate(subPredicates[i])) { | |
return true; | |
} | |
} | |
} | |
if (key === 'and') { | |
subPredicates = expression[key] || []; | |
for (i = 0; i < subPredicates.length; i += 1) { | |
if (!evaluate(subPredicates[i])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment