Store each function in an object, either predefined or dynamically.
If you want to create a feature set, create a comparator object, as shown below. I assumed that you did not extend Object.prototype . If you have done this, operators.hasOwnProperty(property) should be used in the first loop.
// Run only once var funcs = {}; // Optionally, remove `funcs` and swap `funcs` with `operators` var operators = { // at the first loop. '>=': '>=', '<=': '<=', '<' : '<', '>' : '>', '=' : '==', //!! '==':'===', //!! '!=': '!=' }; // Operators // Function constructor used only once, for construction for (var operator in operators) { funcs[operator] = Function('a', 'c', 'return function() {return this[a] ' + operator + ' c};'); } // Run later var comparator = function(a, b, c) { return typeof funcs[b] === 'function' ? funcs[b](a, c) : null; };
When comparator is called, the returned function looks like this:
function() { return this[a] < c; }
This method can be implemented this way ( demo in JSFiddle ):
// Assumed that funcs has been defined function implementComparator(set, key, operator, value) { var comparator, newset = [], i; if (typeof funcs[operator] === 'function') { comparator = funcs[operator](key, value); } else { //If the function does not exist... throw TypeError("Unrecognised operator"); } // Walk through the whole set for (i = 0; i < set.length; i++) { // Invoke the comparator, setting `this` to `set[i]`. If true, push item if (comparator.call(set[i])) { newset.push(set[i]); } } return newset; } var set = [ {meow: 5}, {meow: 3}, {meow: 4}, {meow: 0}, {meow: 9}] implementComparator( set , 'meow', '<=', 5); // equals: [ {meow: 5}, {meow: 3}, {meow: 4}, {meow: 0} ]
For clarification, I built this answer, given the following:
- The OP requests a simple, easily extensible method with an unknown / dynamic set of statements.
- The code is based on the pseudo-code in the OP, without changing anything that could affect the intent of the OP. With some settings, this function can also be used for
Array.prototype.filter or Array.prototype.sort . eval (or Function ) should not be used with every call to comparator