我为选项"filterProductBy (options("编写了一个排序方法,告诉我如何使此方法通用,无论参数数量如何,我都可以应用此过滤器。请告诉我该怎么做?
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
//Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for filtering products by specified parameters
filterProductBy(options) {
const optionName = options.name,
optionCount = options.count,
optionPrice = options.price;
const filters = {
byName: optionName == undefined ? () => undefined :
(actualName, optionName) => actualName === optionName,
byCount: optionCount == undefined ? () => undefined :
new Function("actualName, optionName", "return actualName " + optionCount),
byPrice: optionPrice == undefined ? () => undefined :
new Function("actualName, optionName", "return actualName " + optionPrice)
};
return this.products.filter(
(product) => filters.byName(product.name, optionName)
|| filters.byCount(product.count, optionCount)
|| filters.byPrice(product.price, optionPrice));
}
}
const shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.addProduct(new Product("item 2", 2, 100));
shop.addProduct(new Product("some 3", 30, 300));
console.log(shop.filterProductBy({
name: "product 1",
count: ">=4",
price: ">500"
}));
它不需要那么复杂。只需遍历你得到的对象的属性,如果它与其中任何一个匹配,则包含一个项目(因为你的过滤器是一个"OR"过滤器(:
filterProductBy(options) {
var keys = Object.keys(options);
return this.products.filter(product => keys.some(key => product[key] == options[key]));
}
如果==
不适用于所有选项,则可以在key
上使用switch
(在some
回调中(来选择要使用的正确关系。
现场示例:
var products = [
{name: "Widget", count: 12, price: 100},
{name: "Gadget", count: 2, price: 70},
{name: "Thingy", count: 14, price: 80}
];
function filterProductBy(options) {
var keys = Object.keys(options);
return this.products.filter(product => keys.some(key => product[key] == options[key]));
}
console.log("name: Widget", filterProductBy({name: "Widget"}));
console.log("name: Widget, count: 2", filterProductBy({name: "Widget", count: 2}));
这会将options
的键作为数组获取,然后在filter
回调中使用它们来查看产品是否通过使用some
匹配其中任何一个。
如果你想要一个"AND"过滤器,你会使用every
而不是some
:
filterProductBy(options) {
var keys = Object.keys(options);
return this.products.filter(product => keys.every(key => product[key] == options[key]));
}
现场示例:
var products = [
{name: "Widget", count: 12, price: 100},
{name: "Gadget", count: 2, price: 70},
{name: "Thingy", count: 14, price: 80}
];
function filterProductBy(options) {
var keys = Object.keys(options);
return this.products.filter(product => keys.every(key => product[key] == options[key]));
}
console.log("name: Widget", filterProductBy({name: "Widget"}));
console.log("name: Widget, count: 14", filterProductBy({name: "Widget", count: 14}));
console.log("name: Thingy, count: 14", filterProductBy({name: "Thingy", count: 14}));