Advertisement
Guest User

Untitled

a guest
Feb 18th, 2022
669
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function treasureHunt(arr) {
  2.   let treasureChestItems = arr.shift().split('|');
  3.  
  4.   while (arr[0] !== 'Yohoho!') {
  5.     let tokens = arr.shift().split(' ');
  6.     let command = tokens.shift();
  7.  
  8.     if (command === 'Loot') {
  9.       while (tokens.length) {
  10.         let item = tokens.shift();
  11.         if (!treasureChestItems.includes(item)) {
  12.           treasureChestItems.unshift(item);
  13.         }
  14.       }
  15.     } else if (command === 'Drop') {
  16.       let index = Number(tokens.shift());
  17.       if (index >= 0 && index < treasureChestItems.length) {
  18.         treasureChestItems.push(treasureChestItems.splice(index, 1));
  19.       }
  20.     } else if (command === 'Steal') {
  21.       let count = Math.min(treasureChestItems.length, Number(tokens.shift()));
  22.       let index = treasureChestItems.length - count;
  23.       let stolen = treasureChestItems.splice(index, count);
  24.       console.log(stolen.join(', '));
  25.     }
  26.   }
  27.  
  28.   if (treasureChestItems.length) {
  29.     let averageTreasureGain = treasureChestItems.reduce((prevSum, item) => prevSum + item.length, 0) / treasureChestItems.length;
  30.     console.log(`Average treasure gain: ${averageTreasureGain.toFixed(2)} pirate credits.`);
  31.   } else {
  32.     console.log('Failed treasure hunt.');
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement