Advertisement
TZinovieva

Pirates JS Fundamentals

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