Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function test(arr) {
- let plantInfoCount = Number(arr.shift());
- let plantInfo = {};
- for (let i = 0; i < plantInfoCount; i++) {
- let [plantName, rarity] = arr.shift().split('<->');
- if (!plantInfo[plantName]) {
- plantInfo[plantName] = {};
- }
- plantInfo[plantName]['Rarity'] = Number(rarity);
- plantInfo[plantName]['Rating'] = [];
- }
- let commandInfo = arr.shift();
- while (commandInfo != 'Exhibition') {
- let [command, plantCommandInfo] = commandInfo.split(': ');
- let [plantName, value] = plantCommandInfo.split(' - ');
- switch (command) {
- case 'Rate': ratingHandler(plantName, Number(value)); break;
- case 'Update': updateRarityHandler(plantName, Number(value)); break;
- case 'Reset': resetRatingHandler(plantName); break;
- }
- commandInfo = arr.shift();
- }
- function ratingHandler(plantName, rating) {
- if (!plantInfo[plantName]) {
- console.log('error');
- return;
- }
- plantInfo[plantName]['Rating'].push(rating);
- }
- function updateRarityHandler(plantName, rarity) {
- if (!plantInfo[plantName]) {
- console.log('error');
- return;
- }
- plantInfo[plantName]['Rarity'] = Number(rarity);
- }
- function resetRatingHandler(plantName) {
- if (!plantInfo[plantName]) {
- console.log('error');
- return;
- }
- plantInfo[plantName]['Rating'] = [];
- }
- let avgRatingSort = Object.entries(plantInfo).sort((a, b) => {
- let firstAvgRating = 0;
- let secondAvgRating = 0;
- if (a[1]['Rating'].length !== 0) {
- firstAvgRating = (a[1]['Rating'].reduce((acc, curr) => acc += curr, 0) / a[1]['Rating'].length);
- }
- if (b[1]['Rating'].length !== 0) {
- secondAvgRating = (b[1]['Rating'].reduce((acc, curr) => acc += curr, 0) / b[1]['Rating'].length);
- }
- return secondAvgRating - firstAvgRating;
- });
- let raritySort = avgRatingSort.sort((a, b) => b[1]['Rarity'] - a[1]['Rarity']);
- console.log('Plants for the exhibition:');
- for (let kvp of raritySort) {
- let avgSum = 0;
- if (kvp[1]['Rating'].length > 0) {
- avgSum = (kvp[1]['Rating'].reduce((a, c) => a += c, 0) / kvp[1]['Rating'].length);
- }
- console.log(`- ${kvp[0]}; Rarity: ${kvp[1]['Rarity']}; Rating: ${avgSum.toFixed(2)}`);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement