Advertisement
Lulunga

Battle Manager

Aug 3rd, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. function solve(input) {
  2. let records = {};
  3.  
  4.  
  5. function add(person, health, energy) {
  6. if (!records.hasOwnProperty(person)) {
  7. records[person] = {};
  8. records[person].health = 0;
  9. records[person].energy = energy;
  10. }
  11. records[person].health += health;
  12.  
  13. };
  14.  
  15. function attack(attackerName, defenderName, damage) {
  16. if (records[attackerName] && records[defenderName]) {
  17. records[defenderName].health -= damage;
  18. }
  19. if (records[defenderName].health <= 0) {
  20. console.log(`${defenderName} was disqualified!`);
  21. delete records[defenderName];
  22.  
  23. }
  24. records[attackerName].energy -= 1;
  25. if (records[attackerName].energy <= 0) { //may be without <
  26. console.log(`${attackerName} was disqualified!`);
  27. delete records[attackerName];
  28.  
  29. }
  30.  
  31. };
  32.  
  33. function deletion(userName) {
  34. if (userName === "All") {
  35. for (let prop in records) {
  36. delete records[prop];
  37. }
  38. } else {
  39. if (records.hasOwnProperty(userName)) {
  40. delete records[userName];
  41. }
  42. }
  43. };
  44. for (let line of input) {
  45. if (line === 'Results') {
  46. break;
  47. }
  48. let tokens = line.split(':');
  49. if (tokens !== undefined && tokens !== null) {
  50. let command = tokens.shift();
  51. if (command === 'Add') {
  52. let person = tokens[0];
  53. let health = Number(tokens[1]);
  54. let energy = Number(tokens[2]);
  55. add(person, health, energy);
  56. } else if (command === 'Attack') {
  57. let attackerName = tokens[0];
  58. let defenderName = tokens[1];
  59. let damage = Number(tokens[2]);
  60. attack(attackerName, defenderName, damage);
  61. } else if (command === 'Delete') {
  62. let username = tokens[0];
  63. deletion(username);
  64. }
  65. }
  66.  
  67. }
  68. let countofPeople = 0;
  69. countofPeople = Object.keys(records).length;
  70. if (countofPeople !== 0) {
  71. console.log(`People count: ${countofPeople}`);
  72. }
  73. let sorted = Object.entries(records);
  74. sorted.sort((a, b) => b[1].health - a[1].health || a[0].localeCompare(b[0]));
  75. if (sorted.length > 0) {
  76. sorted.forEach(element => {
  77. console.log(`${element[0]} - ${element[1].health} - ${element[1].energy}`);
  78. });
  79. }
  80.  
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement