stsp93

Untitled

May 6th, 2022 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function armies(input) {
  2.     let armies = []
  3.     //Read input
  4.     input.forEach(el => {
  5.  
  6.         //"{leader} arrives"
  7.         if (el.includes('arrives')) {
  8.             const leader = el.replace(' arrives', '');
  9.             armies.push({ 'leader': leader })
  10.  
  11.             //"{leader}: {army name}, {army count}"
  12.         } else if (el.includes(':')) {
  13.             let [leader, army, count] = el.split(/\W /g);
  14.             count = Number(count);
  15.             armies.forEach(el => {
  16.                 if (el['leader'] === leader) {
  17.                     el[army] = count;
  18.                     if (!el.total) {
  19.                         el.total = count;
  20.                     } else {
  21.                         el.total += count;
  22.                     }
  23.                 }
  24.             })
  25.  
  26.             //"{army name} + {army count}"
  27.         } else if (el.includes('+')) {
  28.             let [army, count] = el.split(' + ');
  29.             count = Number(count);
  30.             armies.forEach(el => {
  31.                 if (el.hasOwnProperty(army)) {
  32.                     el[army] += count;
  33.                     el.total += count;
  34.                 }
  35.             })
  36.  
  37.             //"{leader} defeated"
  38.         } else if (el.includes('defeated')) {
  39.             const leader = el.replace(' defeated', '');
  40.             armies.forEach((el, i) => {
  41.                 if (el['leader'] === leader) {
  42.                     armies.splice(i, 1);
  43.                 }
  44.             })
  45.         }
  46.     })
  47.     //Sort total army count
  48.     armies.sort((a, b) => b.total - a.total);
  49.  
  50.     //Print Output
  51.     armies.forEach(el => {
  52.         // Check if leader has no army
  53.         if (!el.total) {
  54.             el.total = 0
  55.         };
  56.         console.log(`${el['leader']}: ${el['total']}`);
  57.         delete el.leader;
  58.         delete el.total;
  59.         // Sort distinct armies
  60.         let arr = [];
  61.         for (const [army, count] of Object.entries(el)) {
  62.             arr.push([army, count])
  63.         }
  64.         arr.sort((a, b) => b[1] - a[1]);
  65.  
  66.         //Print army
  67.         arr.forEach(el => console.log(`>>> ${el[0]} - ${el[1]}`));
  68.  
  69.     })
  70. }
Add Comment
Please, Sign In to add comment