Advertisement
PPetkov2000

Javascript Fundamentals: Associative Arrays - Armies

Dec 20th, 2019
546
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(params) {
  2.   let armies = {};
  3.   let armyLeaders = [];
  4.  
  5.   for (let param of params) {
  6.     if (param.includes("arrives")) {
  7.       let indexOfArrives = param.indexOf("arrives");
  8.       let leader = param.slice(0, indexOfArrives).trim();
  9.       if (!armies.hasOwnProperty(leader)) {
  10.         armies[leader] = {
  11.           armiesName: {},
  12.           totalArmyCount: 0
  13.         };
  14.       }
  15.       armyLeaders.push(leader);
  16.     } else if (param.includes("defeated")) {
  17.       let indexOfDefeated = param.indexOf("defeated");
  18.       let leader = param.slice(0, indexOfDefeated).trim();
  19.       let indexOfLeader = armyLeaders.indexOf(leader);
  20.       if (armies.hasOwnProperty(leader)) {
  21.         delete armies[leader];
  22.         armyLeaders.splice(indexOfLeader, 1);
  23.       }
  24.     } else if (param.includes(":")) {
  25.       let [leader, army] = param.split(": ");
  26.       let [armyName, armyCount] = army.split(", ");
  27.       if (armies.hasOwnProperty(leader)) {
  28.         if (!armies[leader].armiesName.hasOwnProperty(armyName)) {
  29.           armies[leader].armiesName[armyName] = Number(armyCount);
  30.           armies[leader].totalArmyCount += Number(armyCount);
  31.         }
  32.       }
  33.     } else if (param.includes("+")) {
  34.       let [armyName, armyCount] = param.split(" + ");
  35.       armyLeaders.forEach(leader => {
  36.         for (let army in armies[leader]) {
  37.           if (armies[leader][army].hasOwnProperty(armyName)) {
  38.             armies[leader].armiesName[armyName] += Number(armyCount);
  39.             armies[leader].totalArmyCount += Number(armyCount);
  40.           }
  41.         }
  42.       });
  43.     }
  44.   }
  45.  
  46.   Object.entries(armies)
  47.     .sort((a, b) => b[1].totalArmyCount - a[1].totalArmyCount)
  48.     .forEach(army => {
  49.       console.log(`${army[0]}: ${army[1].totalArmyCount}`);
  50.       Object.values(army[1]).forEach(armyInfo =>
  51.         Object.entries(armyInfo).forEach(a =>
  52.           console.log(`>>> ${a[0]} - ${a[1]}`)
  53.         )
  54.       );
  55.     });
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement