我正在尝试重构以下代码以使用 .filter() 和 .any()。我哪里错了??
目标是退回所有不含坚果或蘑菇的比萨饼。在这两种情况下, productsICanEat.length 应该 === 1。
原始代码:
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]);
}
}
重构代码:
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();