I implemented a method for filtering goods on the specified options. The method takes as an argument an options object that contains parameters for searching, for example: {name: "item 2", price: "<= 1000", count: "> 2"}, each of the options is optional. The method must return a filtered array with the goods. filterProductBy (options).
I managed to filter by name. Tell me how to properly filter by the number so that the filter call looks like this:
console.log(shop.filterProductBy({
name: "product 1",
count: ">1",
price: "<=1000"}));
Code:
//Product Creation Class
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: function (actualName, optionName) {
return (actualName === undefined) || (actualName === optionName);
},
byCount: function (actualCount, optionCount) {
return (actualCount === undefined) || (actualCount === optionCount);
},
byPrice: function (actualPrice, optionPrice) {
return (actualPrice === undefined) || (actualPrice === 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", 3, 500));
shop.addProduct(new Product("anything 4", 4, 1000));