Question:
Create an array "Shopping list". Each element of the array is an object that contains the name of the product, the required quantity and whether it was purchased or not. Write several functions for working with such an array.
-
Displaying the entire list on the screen in such a way that unbought products go first, and then purchased ones.
-
Adding a purchase to the list. Please note that when adding a purchase with an existing product in the list, you need to increase the quantity in the existing purchase, and not add a new one.
In the code, I made the array sorted by status (item purchased or not). Next, I manually created a new object and added it using the push method to the array. I don't understand how you can create a function that will create a new object of this class and add it to the array
class Product {
constructor(nameOfProduct, amount, status) {
this.nameOfProduct = nameOfProduct;
this.amount = amount;
this.status = status;
}
static sortProduct(a) {
if (a.status == 'Не куплен') return -1;
if (a.status == 'Куплен') return 1;
}
static showProduct(a) {
return a.nameOfProduct;
}
}
let shopList = [
new Product('Банан', 2, 'Не куплен'),
new Product('Апельсин', 5,'Куплен'),
new Product('Молоко', 1, 'Куплен'),
new Product('Груша', 10, 'Не куплен'),
];
shopList.sort(Product.sortProduct);
console.log(shopList.map(Product.showProduct));
let newProduct = new Product('Шоколад', 2, 'Не куплен');
shopList.push(newProduct);
shopList.sort(Product.sortProduct);
console.log(shopList.map(Product.showProduct));
Answer:
class Product { constructor(params = {}) { Object.assign(this, { pName: null, amount: 1, bought: false }, { ...params }); } static sortDefault(a, b) { // чтобы сначала шли некупленные продукты, а потом – купленные return (a.bought - b.bought) * 10 + a.pName.localeCompare(b.pName); }; } Product.prototype.toString = function () { return `${this.pName} (x${this.amount}), ${this.bought ? 'куплено' : 'не куплено'}`; }; const shopList = [ { pName: 'Банан', amount: 2 }, { pName: 'Апельсин', amount: 5, bought: true }, { pName: 'Молоко', bought: true }, { pName: 'Груша', amount: 10 } ].map(prodDef => new Product(prodDef)); const addToShopList = prodDef => { // при добавлении покупки с уже существующим в списке продуктом, необходимо увеличивать количество в существующей покупке, а не добавлять новую const prod = shopList.find(prod => prod.pName === prodDef.pName); if (!prod) return shopList.push(new Product(prodDef)); prod.amount += prodDef.amount; }; const printShopList = () => shopList.forEach( (prod, i) => console.log(`${i + 1}. ${prod}`) ); shopList.sort(Product.sortDefault); printShopList(); console.log('---'); addToShopList({ pName: 'Банан', amount: 3 }); addToShopList({ pName: 'Шоколад', amount: 2 }); shopList.sort(Product.sortDefault); printShopList();