Advertisement
Guest User

PlantDiscovery

a guest
Sep 14th, 2020
1,397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function printInfo(input) {
  2.     let plantCount = Number(input.shift());
  3.     let plantCollection = {};
  4.  
  5.     for (let i = 0; i < plantCount; i++) {
  6.         let line = input.shift();
  7.         let [plant, rarity] = line.split('<->');
  8.         rarity = Number(rarity);
  9.         plantCollection[plant] = { rarity, rating: [] };
  10.     }
  11.  
  12.     let line = input.shift();
  13.     while (line !== 'Exhibition') {
  14.         let [command, ...rest] = line.split(': ');
  15.         let [plant, data] = rest[0].split(' - ');
  16.         if (plantCollection.hasOwnProperty(plant)) {
  17.             switch (command) {
  18.                 case 'Rate': {
  19.                     let rating = Number(data);
  20.                     plantCollection[plant].rating.push(rating);
  21.                     break;
  22.                 }
  23.                 case 'Update': {
  24.                     let newRarity = Number(data);
  25.                     plantCollection[plant].rarity = newRarity;
  26.                     break;
  27.                 }
  28.                 case 'Reset': {
  29.                     plantCollection[plant].rating = [];
  30.                     break;
  31.                 }
  32.                 default:
  33.                     console.log('error');
  34.                     break;
  35.             }
  36.         } else {
  37.             console.log('error');
  38.         }
  39.         line = input.shift();
  40.     }
  41.  
  42.     let sortedPlants = Object.keys(plantCollection).sort(
  43.         (a, b) =>
  44.             plantCollection[b].rarity - plantCollection[a].rarity ||
  45.             average(plantCollection[b].rating) - average(plantCollection[a].rating)
  46.     );
  47.  
  48.     console.log(`Plants for the exhibition:`);
  49.  
  50.     for (let plant of sortedPlants) {
  51.         console.log(`- ${plant}; Rarity: ${plantCollection[plant].rarity}; Rating: ${average(plantCollection[plant].rating).toFixed(2)}`);
  52.     }
  53.  
  54.     function average(arr) {
  55.         if (!arr.length) return 0;
  56.         return arr.reduce((a, b) => a + b, 0) / arr.length;
  57.     }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement