bebo231312312321

Untitled

Sep 25th, 2024
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.   const [generateBtn, buyBtn] = Array.from(document.querySelectorAll('button'));
  3.   const [input, output] = Array.from(document.querySelectorAll('textarea'));
  4.   const tbody = document.querySelector('tbody');
  5.  
  6.   generateBtn.addEventListener('click', generate);
  7.   buyBtn.addEventListener('click', buy);
  8.  
  9.   const items = []; // closure
  10.  
  11.   function buy() {
  12.     let list = [];
  13.     let total = 0;
  14.     let decoration = 0;
  15.     let bought = items.filter((i) => i.isChecked());
  16.    
  17.     for (let item of bought) {
  18.       list.push(item.name);
  19.       total += Number(item.price);
  20.       decoration += Number(item.decFactor);
  21.     }
  22.     decoration /= bought.length;
  23.    
  24.     output.value = [
  25.       `Bought furniture: ${list.join(', ')}`,
  26.       `Total price: ${total.toFixed(2)}`,
  27.       `Average decoration factor: ${decoration}`,
  28.     ].join('\n');
  29.   }
  30.  
  31.   function generate() {
  32.     const data = JSON.parse(input.value);
  33.  
  34.     for (let item of data) {
  35.       const row = document.createElement('tr');
  36.  
  37.       row.appendChild(createColumn('img', item.img)); // Image column
  38.       row.appendChild(createColumn('p', item.name)); // Name column
  39.       row.appendChild(createColumn('p', item.price)); // Price column
  40.       row.appendChild(createColumn('p', item.decFactor)); // Decoration column
  41.  
  42.       // Input column
  43.       const c5 = document.createElement('td');
  44.       const checkbox = document.createElement('input');
  45.       checkbox.type = 'checkbox';
  46.       c5.appendChild(checkbox);
  47.       row.appendChild(c5);
  48.  
  49.       tbody.appendChild(row);
  50.  
  51.       items.push({
  52.         ...item,
  53.         isChecked,
  54.       });
  55.  
  56.       function isChecked() {
  57.         return checkbox.checked;
  58.       }
  59.     }
  60.   }
  61.  
  62.   function createColumn(type, content) {
  63.     const result = document.createElement('td');
  64.     let inner;
  65.  
  66.     if (type == 'img') {
  67.       inner = document.createElement('img');
  68.       inner.src = content;
  69.     } else {
  70.       inner = document.createElement('p');
  71.       inner.textContent = content;
  72.     }
  73.     result.appendChild(inner);
  74.     return result;
  75.   }
  76. }
Add Comment
Please, Sign In to add comment