Advertisement
Guest User

HellsKitchen

a guest
Jan 27th, 2021
1,783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.     document.querySelector('#btnSend').addEventListener('click', onClick);
  3.  
  4.     function onClick() {
  5.         let arr = JSON.parse(document.querySelector('#inputs textarea').value);
  6.         let objWinner = findBestRestaurant(arr);
  7.         document.querySelector('#bestRestaurant>p').textContent = getMsgRest(objWinner);
  8.         document.querySelector('#workers>p').textContent = getMsgEmp(objWinner.workers);
  9.     }
  10.  
  11.     function getMsgRest(objWinner) {
  12.         return `Name: ${objWinner.name} Average Salary: ${objWinner.avgSalary.toFixed(2)} Best Salary: ${objWinner.maxSalary.toFixed(2)}`;
  13.     }
  14.  
  15.     function getMsgEmp(workers) {
  16.         return workers.map(w => `Name: ${w.worker} With Salary: ${w.salary}`).join(' ');
  17.     }
  18.  
  19.     function findBestRestaurant(arr) {
  20.         let resultRestaurants = arr.reduce((acc, e) => {
  21.             let [restaurant, ...workers] = e.split(/(?: - )|(?:, )/g);
  22.             workers = workers.map(w => {
  23.                 let [worker, salary] = w.split(' ');
  24.                 return {
  25.                     worker: worker,
  26.                     salary: +salary
  27.                 };
  28.             });
  29.             let foundRestraunt = acc.find(r => r.name === restaurant);
  30.             if (foundRestraunt) {
  31.                 foundRestraunt.workers = foundRestraunt.workers.concat(workers);
  32.             } else {
  33.                 acc.push({
  34.                     name: restaurant,
  35.                     workers: workers
  36.                 });
  37.             }
  38.             return acc;
  39.         }, []);
  40.  
  41.         resultRestaurants.forEach((el, idx) => {
  42.             el.inputOrder = idx;
  43.             el.avgSalary = el.workers.reduce((acc, el) => acc + el.salary, 0) / el.workers.length;
  44.             el.maxSalary = Math.max(...el.workers.map(w => w.salary));
  45.         });
  46.  
  47.         resultRestaurants.sort((a, b) => b.avgSalary - a.avgSalary || a.inputOrder - b.inputOrder);
  48.         let bestRestaurant = resultRestaurants[0];
  49.         bestRestaurant.workers.sort((a, b) => b.salary - a.salary);
  50.  
  51.         return bestRestaurant;
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement