SHARE
TWEET

Untitled

a guest May 24th, 2019 89 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.  
  3.    let buttons = document.querySelectorAll(`div button`);
  4.  
  5.    for (let i = 0; i < buttons.length - 1; i++) {
  6.  
  7.       buttons[i].addEventListener(`click`, addProduct);
  8.    }
  9.  
  10.    buttons[3].addEventListener(`click`, buy);
  11.  
  12.    let products = {};
  13.  
  14.    function addProduct(e) {
  15.  
  16.       let el = e.target.parentNode.parentNode.children;
  17.       console.log(el);
  18.       let name = el[1].children[0].textContent;
  19.       let price = +el[3].textContent;
  20.  
  21.  
  22.       let product = {
  23.          name: name,
  24.          price: price,
  25.          count: 1
  26.       }
  27.  
  28.       if (!products.hasOwnProperty(product.name)) {
  29.          products[product.name] = product;
  30.       } else {
  31.          products[product.name].count++;
  32.       }
  33.  
  34.       let textArea= document.querySelector(`textarea`);
  35.       textArea.value+=`Added ${product.name} for ${product.price.toFixed(2)} to the cart.\n`
  36.    }
  37.  
  38.    function buy() {
  39.  
  40.       let totalPrice = 0;
  41.        let listOfProductNames = []
  42.        for (let p of Object.values(products)) {
  43.  
  44.            totalPrice += p.price * p.count;
  45.            listOfProductNames.push(p.name);
  46.        }
  47.  
  48.        let textArea= document.querySelector(`textarea`);
  49.        textArea.value += `You bought ${listOfProductNames.join(`, `)} for ${totalPrice.toFixed(2)}.\n`;
  50.  
  51.        
  52.        for (let i = 0; i < buttons.length - 1; i++) {
  53.  
  54.          buttons[i].removeEventListener(`click`, addProduct);
  55.       }
  56.    
  57.        buttons[3].removeEventListener(`click`, buy);
  58.    }
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top