Advertisement
bebo231312312321

Untitled

Apr 2nd, 2023
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arrInput) {
  2.    
  3.     let arr = arrInput.slice();
  4.     let currentLine = arr.shift();
  5.     let heroesInfo = {};
  6.  
  7.     while (currentLine !== 'End') {
  8.  
  9.         let tokens = currentLine.split(' ');
  10.         let command = tokens[0];
  11.         let heroName = tokens[1];
  12.         let spellName = '';
  13.  
  14.         if (command === 'Enroll') {
  15.  
  16.             if (!heroesInfo.hasOwnProperty(heroName)) {
  17.                 heroesInfo[heroName] = [];
  18.             } else {
  19.                 console.log(`${heroName} is already enrolled.`);
  20.             }
  21.         } else if (command === 'Learn') {
  22.             spellName = tokens[2];
  23.  
  24.             if (heroesInfo.hasOwnProperty(heroName)) {
  25.  
  26.                 if (!heroesInfo[heroName].includes(spellName)) {
  27.                     heroesInfo[heroName].push(spellName);
  28.                 } else {
  29.                     console.log(`${heroName} has already learnt ${spellName}.`);
  30.                 }
  31.             } else {
  32.                 console.log(`${heroName} doesn't exist.`);
  33.            }
  34.        } else if (command === 'Unlearn') {
  35.            spellName = tokens[2];
  36.  
  37.            if (heroesInfo.hasOwnProperty(heroName)) {
  38.  
  39.                if (!heroesInfo[heroName].includes(spellName)) {
  40.                    console.log(`${heroName} doesn't know ${spellName}.`);
  41.                 } else {
  42.                     let spellToRemoveIndex = heroesInfo[heroName].indexOf(spellName);
  43.                     heroesInfo[heroName].splice(spellToRemoveIndex, 1);
  44.                 }
  45.             } else {
  46.                 console.log(`${heroName} doesn't exist.`);
  47.            }
  48.        }
  49.  
  50.        currentLine = arr.shift();
  51.    }
  52.  
  53.    let unsortedHeroesInfo = Array.from(Object.entries(heroesInfo));
  54.    let sortedHeroesInfo = unsortedHeroesInfo.sort((a, b) => {
  55.        if (a[1].length !== b[1].length) {
  56.            return b[1].length - a[1].length;
  57.        } else {
  58.            return a[0].localeCompare(b[0]);
  59.        }
  60.    });
  61.  
  62.    console.log('Heroes:');
  63.    sortedHeroesInfo.forEach(hero => {
  64.        console.log(`== ${hero[0]}: ${hero[1].join(', ')}`);
  65.    });
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement