georgiev955

Pirates

Jul 19th, 2023
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function pirates(input) {
  2.     let citiesInfo = {};
  3.     let command = input.shift();
  4.    
  5.     while (command !== "Sail") {
  6.         let [city, population, gold] = command.split('||');
  7.         if (!citiesInfo.hasOwnProperty(city)) {
  8.             citiesInfo[city] = {
  9.                 population: 0,
  10.                 gold: 0,
  11.             };
  12.         }
  13.         citiesInfo[city].population += +population;
  14.         citiesInfo[city].gold += +gold;
  15.         command = input.shift();
  16.     }
  17.  
  18.     input.pop();
  19.  
  20.     for (let line of input) {
  21.         let [action, city, ...data] = line.split('=>');
  22.         switch (action) {
  23.             case 'Plunder':
  24.                 let people = +data[0];
  25.                 let gold = +data[1];
  26.                 console.log(`${city} plundered! ${gold} gold stolen, ${people} citizens killed.`);
  27.                 let newGold = citiesInfo[city].gold - gold;
  28.                 let newPeopleCount = citiesInfo[city].population - people;
  29.                 if (newGold <= 0 || newPeopleCount <= 0) {
  30.                     console.log(`${city} has been wiped off the map!`)
  31.                     delete citiesInfo[city];
  32.                 } else {
  33.                     citiesInfo[city].population = newPeopleCount;
  34.                     citiesInfo[city].gold = newGold;
  35.                 }
  36.                 break;
  37.             case 'Prosper':
  38.                 let goldToAdd = Number(data[0]);
  39.                 if (goldToAdd > 0) {
  40.                     citiesInfo[city].gold += goldToAdd;
  41.                     console.log(`${goldToAdd} gold added to the city treasury. ${city} now has ${citiesInfo[city].gold} gold.`)
  42.                 } else {
  43.                     console.log("Gold added cannot be a negative number!");
  44.                 }
  45.                 break;
  46.         }
  47.     }
  48.     let citiesCount = Object.keys(citiesInfo).length;
  49.     if (citiesCount === 0) {
  50.         console.log("Ahoy, Captain! All targets have been plundered and destroyed!");
  51.     } else {
  52.         console.log(`Ahoy, Captain! There are ${citiesCount} wealthy settlements to go to:`);
  53.         for (const city in citiesInfo) {
  54.             console.log(`${city} -> Population: ${citiesInfo[city].population} citizens, Gold: ${citiesInfo[city].gold} kg`);
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment