Advertisement
Ggodly

za stanku

Dec 3rd, 2021
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function test(arr) {
  2.   let plantInfoCount = Number(arr.shift());
  3.   let plantInfo = {};
  4.  
  5.   for (let i = 0; i < plantInfoCount; i++) {
  6.     let [plantName, rarity] = arr.shift().split('<->');
  7.  
  8.     if (!plantInfo[plantName]) {
  9.       plantInfo[plantName] = {};
  10.     }
  11.  
  12.     plantInfo[plantName]['Rarity'] = Number(rarity);
  13.     plantInfo[plantName]['Rating'] = [];
  14.   }
  15.  
  16.   let commandInfo = arr.shift();
  17.  
  18.   while (commandInfo != 'Exhibition') {
  19.     let [command, plantCommandInfo] = commandInfo.split(': ');
  20.     let [plantName, value] = plantCommandInfo.split(' - ');
  21.  
  22.     switch (command) {
  23.       case 'Rate': ratingHandler(plantName, Number(value)); break;
  24.       case 'Update': updateRarityHandler(plantName, Number(value)); break;
  25.       case 'Reset': resetRatingHandler(plantName); break;
  26.     }
  27.  
  28.     commandInfo = arr.shift();
  29.   }
  30.  
  31.   function ratingHandler(plantName, rating) {
  32.     if (!plantInfo[plantName]) {
  33.       console.log('error');
  34.       return;
  35.     }
  36.  
  37.     plantInfo[plantName]['Rating'].push(rating);
  38.   }
  39.  
  40.   function updateRarityHandler(plantName, rarity) {
  41.     if (!plantInfo[plantName]) {
  42.       console.log('error');
  43.       return;
  44.     }
  45.  
  46.     plantInfo[plantName]['Rarity'] = Number(rarity);
  47.   }
  48.  
  49.   function resetRatingHandler(plantName) {
  50.     if (!plantInfo[plantName]) {
  51.       console.log('error');
  52.       return;
  53.     }
  54.  
  55.     plantInfo[plantName]['Rating'] = [];
  56.   }
  57.  
  58.   let avgRatingSort = Object.entries(plantInfo).sort((a, b) => {
  59.     let firstAvgRating = 0;
  60.     let secondAvgRating = 0;
  61.  
  62.     if (a[1]['Rating'].length !== 0) {
  63.       firstAvgRating = (a[1]['Rating'].reduce((acc, curr) => acc += curr, 0) / a[1]['Rating'].length);
  64.     }
  65.  
  66.     if (b[1]['Rating'].length !== 0) {
  67.       secondAvgRating = (b[1]['Rating'].reduce((acc, curr) => acc += curr, 0) / b[1]['Rating'].length);
  68.     }
  69.  
  70.     return secondAvgRating - firstAvgRating;
  71.   });
  72.  
  73.   let raritySort = avgRatingSort.sort((a, b) => b[1]['Rarity'] - a[1]['Rarity']);
  74.  
  75.   console.log('Plants for the exhibition:');
  76.  
  77.   for (let kvp of raritySort) {
  78.     let avgSum = 0;
  79.  
  80.     if (kvp[1]['Rating'].length > 0) {
  81.       avgSum = (kvp[1]['Rating'].reduce((a, c) => a += c, 0) / kvp[1]['Rating'].length);
  82.     }
  83.  
  84.     console.log(`- ${kvp[0]}; Rarity: ${kvp[1]['Rarity']}; Rating: ${avgSum.toFixed(2)}`);
  85.   }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement