Advertisement
kstoyanov

03. Nikulden’s meals js exam

Aug 12th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arg) {
  2.   let lineInput = arg.shift();
  3.  
  4.   const guests = [];
  5.  
  6.  
  7.   while (lineInput !== 'Stop') {
  8.     const [command, guest, meal] = lineInput.split('-');
  9.  
  10.     switch (command) {
  11.       case 'Like':
  12.         const guestObj = {};
  13.         const isFound = guests.some((g) => g.name === guest);
  14.  
  15.         if (!isFound) {
  16.           guestObj.name = guest;
  17.           guestObj.likeMeals = [];
  18.           guestObj.unlikeMeal = [];
  19.           guests.push(guestObj);
  20.         }
  21.  
  22.         guests.forEach((el) => {
  23.           const { name, likeMeals } = el;
  24.  
  25.           const haveMeal = likeMeals.some((m) => m === meal);
  26.  
  27.           if (name === guest && !haveMeal) {
  28.             likeMeals.push(meal);
  29.           }
  30.         });
  31.  
  32.         break;
  33.       case 'Unlike':
  34.  
  35.         const isF = guests.some((g) => g.name === guest);
  36.  
  37.         if (isF) {
  38.           guests.forEach((el) => {
  39.             const { name, likeMeals, unlikeMeal } = el;
  40.  
  41.  
  42.             if (name === guest) {
  43.               const haveMeal = likeMeals.some((m) => m === meal);
  44.  
  45.               if (haveMeal) {
  46.                 const takeIndex = likeMeals.indexOf(meal);
  47.  
  48.                 unlikeMeal.push(meal);
  49.                 likeMeals.splice(takeIndex, 1);
  50.  
  51.                 console.log(`${guest} doesn't like the ${meal}.`);
  52.              } else {
  53.                console.log(`${guest} doesn't have the ${meal} in his/her collection.`);
  54.               }
  55.             }
  56.           });
  57.         } else {
  58.           console.log(`${guest} is not at the party.`);
  59.         }
  60.  
  61.         break;
  62.       default:
  63.         break;
  64.     }
  65.  
  66.  
  67.     lineInput = arg.shift();
  68.   }
  69.  
  70.  
  71.   const sortGuest = guests.sort((a, b) => b.likeMeals.length - a.likeMeals.length || a.name.localeCompare(b.name));
  72.   let totalUnlikeMeal = 0;
  73.   sortGuest.forEach((el) => {
  74.     const { name, likeMeals, unlikeMeal } = el;
  75.     totalUnlikeMeal += unlikeMeal.length;
  76.  
  77.     console.log(`${name}: ${likeMeals.join(', ')}`);
  78.   });
  79.   console.log(`Unliked meals: ${totalUnlikeMeal}`);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement