Advertisement
Guest User

shopping cart

a guest
Jan 29th, 2020
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.    let titles = document.getElementsByClassName('product-title');
  3.    let prices = document.getElementsByClassName('product-line-price');
  4.    let textArea = document.getElementsByTagName('textarea')[0];
  5.    let allButtons = Array.from(document.getElementsByTagName('button'));
  6.  
  7.    if (titles === null || prices === null || textArea === null || allButtons === null) {
  8.       throw new Error('Error...');
  9.    }
  10.  
  11.    let totalPrice = 0;
  12.    let list = [];
  13.    let endShopping = false;
  14.  
  15.    allButtons.map(b => b.addEventListener('click', eventHandler));
  16.  
  17.    function eventHandler(e) {
  18.       let clickedButton = e.target;
  19.       let clickedButtonClass = clickedButton.className;
  20.       let index = allButtons.indexOf(clickedButton)
  21.  
  22.       if (clickedButtonClass === 'add-product' && endShopping === false) {
  23.          let product = titles[index].innerHTML;
  24.          let price = prices[index].innerHTML;
  25.  
  26.          addProduct(product, price, list);
  27.  
  28.       } else if (clickedButtonClass === 'checkout' && endShopping === false) {
  29.          checkout(list, totalPrice);
  30.  
  31.       }
  32.    }
  33.  
  34.    function addProduct(product, price, list) {
  35.  
  36.       totalPrice += Number(price);
  37.  
  38.       addProductToList(product, list);
  39.  
  40.       textArea.innerHTML += `Added ${product} for ${price} to the cart.\n`;
  41.    }
  42.  
  43.    function addProductToList(prod, list) {
  44.       list.includes(prod) ? list : list.push(prod);
  45.    }
  46.  
  47.    function checkout(list, totalPrice) {
  48.       textArea.innerHTML += `You bought ${list.join(', ')} for ${totalPrice.toFixed(2)}.`;
  49.       endShopping = true;
  50.    }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement