user2033412
user2033412

Reputation: 2119

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.

Upvotes: 4

Views: 1094

Answers (2)

Giorgi Kandelaki
Giorgi Kandelaki

Reputation: 798

May be you can use reduce function here, something like this:

function filterMyProducts(criteria) {
  return criteria.reduce(function(prev, curr) {
    return prev.filter(curr)
  }, products)
}

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239623

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

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

Working Demo

Upvotes: 8

Related Questions