Advertisement
George_Ivanov05

0.2

Jul 9th, 2021
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function tresureHunt(array) {
  2.     let initialTresure = array.shift().split('|');
  3.     let total = 0;
  4.     let isIndexValid = (index, arr) => index >= 0 && index < arr.length;
  5.  
  6.     for (const line of array) {
  7.         let [command, ...elements] = line.split(' ');
  8.  
  9.         if (command === 'Yohoho!') {
  10.             break;
  11.         }
  12.  
  13.         if (command === 'Loot') {
  14.             for (const item of elements) {
  15.                 if (!initialTresure.includes(item)) {
  16.                     initialTresure.unshift(item);
  17.                 }
  18.             }
  19.         } else if (command === 'Drop') {
  20.             let index = Number(elements[0]);
  21.             if (isIndexValid(index, initialTresure)) {
  22.                 let dropped = initialTresure.splice(index, 1);
  23.                 initialTresure.push(...dropped);
  24.             }
  25.         } else if (command === 'Steal') {
  26.             let index = Number(elements[0]);
  27.             let stealedTresure = initialTresure.slice(-index);
  28.             initialTresure.splice(-index);
  29.             console.log(stealedTresure.join(', '));
  30.         }
  31.     }
  32.     total = initialTresure
  33.         .reduce((sum, initialTresure) => sum + initialTresure.length, 0) / initialTresure.length;
  34.  
  35.     if (initialTresure.length > 0) {
  36.         return `Average treasure gain: ${total.toFixed(2)} pirate credits.`
  37.     } else {
  38.         return "Failed treasure hunt."
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement