function isSingle(filter) {
return (filter && 'o' in filter && 'm' in filter && 'v' in filter);
}
function isComposite(filter) {
return (filter && 'lo' in filter);
}
function createBody(filter) {
if (isComposite(filter)) {
var bdy = "";
if (filter.v.length > 1) {
var o = filter.lo;
return "(" + createBody(filter.v.shift()) + " " + o + " " + createBody({ lo: filter.lo, v: filter.v }) + ")";
} else if (filter.v.length == 1) {
return createBody(filter.v.shift());
}
return bdy;
} else if (isSingle(filter)) {
var o = filter.o;
if (typeof filter.v == "string") filter.v = "'" + filter.v + "'"
return "item." + filter.m + " " + o + " " + filter.v;
}
}
var createFunc = function (filter) {
var body = createBody(filter);
var f = new Function("item", " return " + body + ";");
return f;
}
function applyFilter(input, filter) {
if (filter == undefined) {
return input;
}
var fun = createFunc(filter);
var output = input.filter(fun);
return output;
};
var filterQuery1 = { m: "item.type", o: "==", v: "metal" };
var filterQuery2 = { m: "item.size", o: ">", v: 8 };
var filterQuery3 = {
lo: "&&", v: [
{ m: "item.type", o: "==", v: "metal" },
{ m: "item.size", o: "<", v: 9 }]
};
var data = [
{ item: { type: 'wood', size: 10 } },
{ item: { type: 'wood', size: 8 } },
{ item: { type: 'metal', size: 8 } }
]
var result = applyFilter(data, filterQuery1);
console.log(result);
https://jsfiddle.net/kd0kL098/
r.filter(comp, ["type","wood"]).filter(comp, ["size",8]);
- dandavis