Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve3(input) {
- input.pop();
- let heroes = {};
- for (const line of input) {
- let [command, heroName, spellName] = line.split(' ');
- if (command === 'Enroll') {
- if (heroes[heroName]) {
- console.log(`${heroName} is already enrolled.`);
- } else {
- heroes[heroName] = [];
- }
- } else if (command === 'Learn') {
- if (!heroes[heroName]) {
- console.log(`${heroName} doesn't exist.`);
- } else if (heroes[heroName].includes(spellName)) {
- console.log(`${heroName} has already learnt ${spellName}.`);
- } else {
- heroes[heroName].push(spellName);
- }
- } else if (command === 'Unlearn') {
- if (!heroes[heroName]) {
- console.log(`${heroName} doesn't exist.`);
- } else if (heroes[heroName].includes(spellName)) {
- let index = heroes[heroName].indexOf(spellName);
- heroes[heroName].splice(index, 1);
- } else if (!heroes[heroName].includes(spellName)) {
- console.log(`${heroName} doesn't know ${spellName}.`);
- }
- }
- }
- let heroesArr = Object.entries(heroes);
- function sortHeroes(heroA, heroB) {
- let [nameA, spellA] = heroA;
- let countA = spellA.length;
- let [nameB, spellB] = heroB;
- let countB = spellB.length;
- if (countA === countB) {
- return nameA.localeCompare(nameB);
- } else {
- return countB - countA;
- }
- }
- heroesArr.sort(sortHeroes);
- let sortedHeroes = Object.fromEntries(heroesArr);
- console.log('Heroes:');
- for (const hero in sortedHeroes) {
- let spells = sortedHeroes[hero].join(', ');
- console.log(`== ${hero}: ${spells}`);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement