SHARE
TWEET

Untitled

a guest Mar 26th, 2020 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve3(input) {
  2.     input.pop();
  3.     let heroes = {};
  4.  
  5.     for (const line of input) {
  6.         let [command, heroName, spellName] = line.split(' ');
  7.  
  8.         if (command === 'Enroll') {
  9.             if (heroes[heroName]) {
  10.                 console.log(`${heroName} is already enrolled.`);
  11.             } else {
  12.                 heroes[heroName] = [];
  13.             }
  14.  
  15.         } else if (command === 'Learn') {
  16.             if (!heroes[heroName]) {
  17.                 console.log(`${heroName} doesn't exist.`);
  18.            } else if (heroes[heroName].includes(spellName)) {
  19.                console.log(`${heroName} has already learnt ${spellName}.`);
  20.            } else {
  21.                heroes[heroName].push(spellName);
  22.            }
  23.  
  24.        } else if (command === 'Unlearn') {
  25.            if (!heroes[heroName]) {
  26.                console.log(`${heroName} doesn't exist.`);
  27.             } else if (heroes[heroName].includes(spellName)) {
  28.                 let index = heroes[heroName].indexOf(spellName);
  29.                 heroes[heroName].splice(index, 1);
  30.             } else if (!heroes[heroName].includes(spellName)) {
  31.                 console.log(`${heroName} doesn't know ${spellName}.`);
  32.            }
  33.        }
  34.    }
  35.  
  36.    let heroesArr = Object.entries(heroes);
  37.  
  38.    function sortHeroes(heroA, heroB) {
  39.        let [nameA, spellA] = heroA;
  40.        let countA = spellA.length;
  41.  
  42.        let [nameB, spellB] = heroB;
  43.        let countB = spellB.length;
  44.  
  45.        if (countA === countB) {
  46.            return nameA.localeCompare(nameB);
  47.        } else {
  48.            return countB - countA;
  49.        }
  50.    }
  51.  
  52.    heroesArr.sort(sortHeroes);
  53.  
  54.    let sortedHeroes = Object.fromEntries(heroesArr);
  55.  
  56.    console.log('Heroes:');
  57.    
  58.  
  59.    for (const hero in sortedHeroes) {
  60.        let spells = sortedHeroes[hero].join(', ');
  61.        console.log(`== ${hero}: ${spells}`);
  62.    }
  63.    
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top