Advertisement
avr39ripe

jsShopListSimpleClass

Mar 10th, 2021
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Study</title>
  6. </head>
  7. <body>
  8.     <ul id="output">
  9.     </ul>
  10.     <script>
  11.         /*Задание 1
  12.         Создать массив «Список покупок». Каждый элемент массива
  13.         является объектом, который содержит название продукта, необходимое количество и куплен или нет. Написать несколько функций для работы с таким массивом.
  14.         1. Вывод всего списка на экран таким образом, чтобы сначала
  15.         шли некупленные продукты, а потом – купленные.
  16.         2. Добавление покупки в список. Учтите, что при добавлении
  17.         покупки с уже существующим в списке продуктом, необходимо увеличивать количество в существующей покупке,
  18.         а не добавлять новую.
  19.         3. Покупка продукта. Функция принимает название продукта
  20.         и отмечает его как купленный.*/
  21.  
  22.         `use strict`
  23.  
  24.         function ShopList() {
  25.             this._shopList = [];
  26.             this.print = function(printer = (str) => console.log(str)) {
  27.                 for (let it of this._shopList.slice().sort((a, b) => a.bought - b.bought)) {
  28.                     printer(`name: ${it.name} quantity: ${it.qty} bought: ${it.bought}`);
  29.                 }
  30.             };
  31.  
  32.             this.findItemByName = function (name) {
  33.                 return this._shopList.find((it) => it.name == name);
  34.             };
  35.  
  36.             this.addProduct = function (product, qty = 1) {
  37.                 let listItem = this.findItemByName(product);
  38.                 if (listItem) {
  39.                     listItem.qty += qty;
  40.                     return false;
  41.                 }
  42.                 this._shopList.push({ name: product, qty: qty, bought: false });
  43.                 return false;
  44.             };
  45.             this.buyProduct = function(product) {
  46.                 let listItem = this.findItemByName(product);
  47.                 if (listItem) {
  48.                     listItem.bought = true;
  49.                     return true;
  50.                 }
  51.                 return false;
  52.             }
  53.  
  54.         }
  55.                
  56.         {
  57.             // non-interactive test
  58.             let shopListOne = new ShopList();
  59.  
  60.             shopListOne.addProduct('milk', 2);
  61.             shopListOne.addProduct('tea', 1);
  62.             shopListOne.addProduct('orange', 3);
  63.             shopListOne.addProduct('bread', 2);
  64.             shopListOne.addProduct('coffe', 1);
  65.  
  66.             shopListOne.print();
  67.             shopListOne.buyProduct('milk');
  68.             shopListOne.buyProduct('bread');
  69.             console.log('###');
  70.             shopListOne.print();
  71.             shopListOne.buyProduct('lemon');
  72.             console.log('###');
  73.             shopListOne.print();
  74.             shopListOne.addProduct('orange', 2);
  75.             shopListOne.addProduct('meat', 3);
  76.             console.log('###');
  77.             shopListOne.print();
  78.                      
  79.             // interactive test
  80.             // shopList = []; // clear shoping list
  81.             // No need to clear ONE shopList, just create new one!
  82.  
  83.             let shopListTwo = new ShopList();
  84.             let productName;
  85.  
  86.             console.log('So, lets prepare for shopping! Fill in your shopping list!');
  87.             do {
  88.                 shopListTwo.addProduct(prompt('Product name'), +prompt('Product quantity'));
  89.                 shopListTwo.print();
  90.                 console.log('###');
  91.             } while (confirm('Add more products?'));
  92.  
  93.             console.log('Ok, shopping list is ready! Shopping time!');
  94.             shopListTwo.print();
  95.             console.log('###');
  96.  
  97.             do {
  98.                 productName = prompt('Product name');
  99.                 if (shopListTwo.buyProduct(productName)) {
  100.                     console.log(`${productName} bought successfuly!`);
  101.                 }
  102.                 else {
  103.                     console.log(`${productName}: no such product in the shopping list!`);
  104.                 }
  105.                 shopListTwo.print();
  106.                 console.log('###');
  107.             } while (confirm('Buy more products?'));
  108.  
  109.             console.log('### Both shopLists are still alive! ###');
  110.             console.log('### shopListOne ###');
  111.             shopListOne.print();
  112.             console.log('### shopListTwo ###');
  113.             shopListTwo.print();
  114.         }
  115.     </script>
  116. </body>
  117. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement