Advertisement
Pijomir

Treasure Hunt

Oct 11th, 2023 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function manageChestContent(input) {
  2.     let chestContent = input.shift().split('|');
  3.     let commands = {'Loot': loot, 'Drop' : drop, 'Steal': steal};
  4.  
  5.     for (let el of input) {
  6.         let currentEl = el.split(' ');
  7.         let currentCommand = currentEl.shift();
  8.         if (currentCommand === 'Yohoho!') {
  9.             break;
  10.         }
  11.  
  12.         commands[currentCommand](chestContent, currentEl);
  13.     }
  14.  
  15.     let treasureGain = 0;
  16.     chestContent.forEach(a => treasureGain += a.length);
  17.     let averageTreasureGain = treasureGain / chestContent.length;
  18.     console.log(chestContent.length === 0 ? 'Failed treasure hunt.' : `Average treasure gain: ${averageTreasureGain.toFixed(2)} pirate credits.`);
  19.  
  20.     function loot(arr, input) {
  21.         for ( let item of input) {
  22.             if (!arr.includes(item)) {
  23.                 arr.unshift(item);
  24.             }
  25.         }
  26.     }
  27.  
  28.     function drop(arr, index) {
  29.         index = Number(index[0]);
  30.         if (arr[index]) {
  31.             let droppedLoot = arr.splice(index, 1);
  32.             arr.push(droppedLoot[0]);
  33.         }
  34.     }
  35.  
  36.     function steal(arr, count) {
  37.         count = Number(count[0]);
  38.         let stealedItemsCount = Math.min(count, arr.length);
  39.         let stealedItems = arr.splice(arr.length - stealedItemsCount);
  40.         console.log(stealedItems.join(', '));
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement