vasil-y-vasilev

Inventory

Jul 3rd, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let inventoryInput = input.shift();
  3.     let inventory = inventoryInput.split(', ');
  4.  
  5.     let commandLine = input.shift();
  6.     while (commandLine != 'Craft!') {
  7.         let [command, argument] = commandLine.split(' - ');
  8.  
  9.         switch (command) {
  10.             case 'Collect':
  11.                 collectItem(inventory, argument);
  12.  
  13.                 inventory = collectItem(inventory, argument)
  14.                 break;
  15.             case 'Drop':
  16.                 dropItem(inventory, argument);
  17.                 break;
  18.             case 'Combine Items':
  19.                 let [oldItem, newItem] = argument.split(':');
  20.                 combineItems(inventory, oldItem, newItem);
  21.                 break;
  22.             case 'Renew':
  23.                 renewItem(inventory, argument);
  24.                 break;
  25.         }
  26.  
  27.  
  28.         commandLine = input.shift();
  29.     }
  30.  
  31.     function collectItem(inventory, item) {
  32.         if (!inventory.includes(item)) {
  33.             inventory.push(item);
  34.         }
  35.     }
  36.  
  37.     function dropItem(inventory, item) {
  38.         let itemIndex = inventory.indexOf(item);
  39.  
  40.         if (itemIndex > -1) {
  41.             inventory.splice(itemIndex, 1);
  42.         }
  43.     }
  44.  
  45.     function combineItems(inventory, oldItem, newItem) {
  46.         let oldItemIndex = inventory.indexOf(oldItem);
  47.  
  48.         if (oldItemIndex > -1) {
  49.             inventory.splice(oldItemIndex + 1 , 0, newItem);
  50.         }
  51.     }
  52.  
  53.     function renewItem(inventory, item) {
  54.         let itemIndex = inventory.indexOf(item);
  55.  
  56.         if (itemIndex > -1) {
  57.             inventory.splice(itemIndex, 1);
  58.             inventory.push(item);
  59.         }
  60.     }
  61.  
  62.     // Print inventory
  63.     let result = inventory.join(', ');
  64.     console.log(result);
  65. }
  66.  
  67. solve(['Iron, Wood, Sword', 'Collect - Gold', 'Drop - Wood', 'Combine Items - Sword:JP', 'Renew - Sword', 'Craft!']);
Advertisement
Add Comment
Please, Sign In to add comment