collenjones
collenjones

Reputation: 530

What am I doing wrong with my use of _().any()?

I'm trying to refactor the following code to use .filter() and .any(). Where am I going wrong??

The goal is to return all pizzas that do not contain nuts or mushrooms. In both instances, productsICanEat.length should === 1.

Original Code:

products = [
   { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
   { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
   { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
   { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
   { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];

var i,j,hasMushrooms, productsICanEat = [];

for (i = 0; i < products.length; i+=1) {
    if (products[i].containsNuts === false) {
        hasMushrooms = false;
        for (j = 0; j < products[i].ingredients.length; j+=1) {
           if (products[i].ingredients[j] === "mushrooms") {
              hasMushrooms = true;
           }
        }
        if (!hasMushrooms) productsICanEat.push(products[i]);
    }
}

Refactored Code:

var productsICanEat = [];

  /* solve using filter() & all() / any() */
  productsICanEat = _(products).chain()
              .filter(function(product) { 
                if(product.containsNuts === false) 
                  return product; 
                })
              .any(function(product) {

                if(product.ingredients.indexOf('mushrooms') === -1)
                  return true;
                else
                  return false;

              }).value();

Upvotes: 0

Views: 101

Answers (2)

Divey
Divey

Reputation: 1719

You can do this just with filter. The function used by the filter iterator should return a boolean value based on whether it should be included in productsICanEat:

productsICanEat = _(products).chain().filter(function(product) { 
    return !product.containsNuts && (product.ingredients.indexOf('mushrooms') === -1); 
});

Upvotes: 2

Dogbert
Dogbert

Reputation: 222128

You're over complicating it.

var productsICanEat = _(products).filter(function(product) {
    return !product.containsNuts && product.ingredients.indexOf("mushrooms") === -1;
});

http://jsfiddle.net/Dogbert/Ap9LR/

Upvotes: 1

Related Questions