Advertisement
didkoslawow

Untitled

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