Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Concat boolean functions

I want to write a method which filters data for multiple criteria. These criteria should by passed as functions to the filter-function, for example:

var products = [/* some data */];
function filterMyProducts(criteria) {
   return products.filter(/* I'm asking for this code */);
}

function cheap(product) {
    return product.price < 100;
}

function red(product) {
    return product.color == "red";
}

// find products that are cheap and red
var result = filterMyProducts([cheap, red]);

How can I combine the criteria passed in the array to the filter-function? I want them to be combined with a boolean AND.

like image 221
user2033412 Avatar asked Oct 16 '25 13:10

user2033412


1 Answers

function validateProduct(listOfFunctions) {
    return function(currentProduct) {
        return listOfFunctions.every(function(currentFunction) {
            return currentFunction(currentProduct);
        });
    }
}

function filterMyProducts(criteria) {
    return products.filter(validateProduct(criteria));
}

Working Demo

like image 105
thefourtheye Avatar answered Oct 19 '25 12:10

thefourtheye