Advertisement
kstoyanov

03. Hero Recruitment js exam

Aug 11th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(args) {
  2.   let commandLine = args.shift();
  3.   const heroes = {};
  4.   while (commandLine !== 'End') {
  5.     const [commmand, heroName, spellName] = commandLine.split(' ');
  6.  
  7.     switch (commmand) {
  8.       case 'Enroll':
  9.  
  10.  
  11.         if (Object.prototype.hasOwnProperty.call(heroes, heroName)) {
  12.           console.log(`${heroName} is already enrolled.`);
  13.         } else {
  14.           heroes[heroName] = heroName;
  15.           heroes[heroName] = [];
  16.         }
  17.  
  18.         break;
  19.       case 'Learn':
  20.         if (Object.prototype.hasOwnProperty.call(heroes, heroName)) {
  21.           const spellIsFind = heroes[heroName].some((spell) => spell === spellName);
  22.           if (spellIsFind) {
  23.             console.log(`${heroName} has already learnt ${spellName}.`);
  24.           } else {
  25.             heroes[heroName].push(spellName);
  26.           }
  27.         } else {
  28.           console.log(`${heroName} doesn't exist.`);
  29.        }
  30.        break;
  31.      case 'Unlearn':
  32.        if (Object.prototype.hasOwnProperty.call(heroes, heroName)) {
  33.          const spellIsFind = heroes[heroName].some((spell) => spell === spellName);
  34.          if (spellIsFind) {
  35.            const takeIndex = heroes[heroName].indexOf(spellName);
  36.            heroes[heroName] = heroes[heroName].splice(takeIndex, 0);
  37.          } else {
  38.            console.log(`${heroName} doesn't know ${spellName}.`);
  39.           }
  40.         } else {
  41.           console.log(`${heroName} doesn't exist.`);
  42.        }
  43.        break;
  44.  
  45.      default:
  46.        break;
  47.    }
  48.  
  49.  
  50.    commandLine = args.shift();
  51.  }
  52.  
  53.  
  54.  console.log('Heroes:');
  55.  const sortedHeroes = Object.entries(heroes).sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
  56.  
  57.  sortedHeroes.forEach((el) => {
  58.    const [heroName, spellbook] = el;
  59.  
  60.    if (heroes[heroName]) {
  61.      const spells = spellbook.join(', ');
  62.      console.log(`== ${heroName}: ${spells}`);
  63.    }
  64.  });
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement