Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. function solve(arr) {
  2. const heroes = {};
  3.  
  4. for (let i = 0; i < arr.length; i++) {
  5. const [command, heroName, spellName] = arr[i].split(" ");
  6.  
  7. if (command === "End") {
  8. break;
  9. }
  10.  
  11. if (command === "Enroll") {
  12. if (heroes[heroName]) {
  13. console.log(`${heroName} is already enrolled.`);
  14. } else {
  15. heroes[heroName] = [];
  16. }
  17. } else if (command === "Learn") {
  18. if (heroes[heroName]) {
  19. if (heroes[heroName].includes(spellName)) {
  20. console.log(`${heroName} has already learnt ${spellName}.`);
  21. } else {
  22. heroes[heroName].push(spellName);
  23. }
  24. } else {
  25. console.log(`${heroName} doesn't exist.`);
  26. }
  27. } else if (command === "Unlearn") {
  28. if (heroes[heroName]) {
  29. if (heroes[heroName].includes(spellName)) {
  30. const index = heroes[heroName].indexOf(spellName);
  31. heroes[heroName].splice(index, 1);
  32. } else {
  33. console.log(`${heroName} doesn't know ${spellName}.`);
  34. }
  35. } else {
  36. console.log(`${heroName} doesn't exist.`);
  37. }
  38. }
  39. }
  40.  
  41. console.log("Heroes:");
  42.  
  43. Object.keys(heroes)
  44. .sort((hero1, hero2) => {
  45. const hero1Spells = heroes[hero1];
  46. const hero2Spells = heroes[hero2];
  47.  
  48. if (hero1Spells.length > hero2Spells.length) {
  49. return -1;
  50. } else if (hero1Spells.length < hero2Spells.length) {
  51. return 1;
  52. } else {
  53. return hero1.localeCompare(hero2);
  54. }
  55. })
  56. .forEach(hero => {
  57. console.log(`== ${hero}: ${heroes[hero].join(", ")}`);
  58. });
  59. }
  60.  
  61. solve([
  62. `Enroll Stefan`,
  63. `Enroll Pesho`,
  64. `Enroll Stefan`,
  65. `Learn Stefan ItShouldWork`,
  66. `Learn Stamat ItShouldNotWork`,
  67. `Unlearn Gosho Dispel`,
  68. `Unlearn Stefan ItShouldWork`,
  69. `End`
  70. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement