MartenBG

Treasure Hunt

Oct 28th, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. function treasureHunt(line) {
  2.  
  3. let treasure = line
  4. .shift()
  5. .split('|');
  6.  
  7. line.forEach(tr => {
  8.  
  9. let current = tr.split(' ');
  10. let command = current.shift();
  11.  
  12. if (command === 'Yohoho!') {
  13. return;
  14. }
  15.  
  16. if (command === 'Loot') {
  17.  
  18. for (let i = 0; i < current.length; i++) {
  19.  
  20. if (!treasure.includes(current[i])) {
  21.  
  22. treasure.unshift(current[i]);
  23. }
  24. }
  25. }
  26. if (command === 'Drop') {
  27. let index = Number(current[0]);
  28. let moved = treasure[index];
  29. if (index >= 0) {
  30. treasure.splice(index, 1);
  31. treasure.push(moved);
  32. }
  33.  
  34. }
  35. if (command === 'Steal') {
  36. let stolenItems = '';
  37. let index = Number(current[0]);
  38.  
  39. if (index < treasure.length) {
  40.  
  41. stolenItems = treasure.splice(treasure.length - index, index);
  42. console.log(stolenItems.join(', '));
  43.  
  44. } else {
  45.  
  46. stolenItems = treasure.splice(0).join(', ');
  47. console.log(stolenItems);
  48. }
  49. }
  50. });
  51.  
  52. let numberOfLoots = treasure.length;
  53. let points = treasure
  54. .join('')
  55. .length;
  56.  
  57. if (numberOfLoots > 0) {
  58. console.log(`Average treasure gain: ${(points / numberOfLoots).toFixed(2)} pirate credits.`);
  59. } else {
  60. console.log("Failed treasure hunt.");
  61. }
  62. }
  63.  
  64. treasureHunt([
  65. 'Diamonds|Silver|Shotgun|Gold',
  66. 'Loot Silver Medals Coal',
  67. 'Drop -1',
  68. 'Drop 1',
  69. 'Steal 12',
  70. 'Yohoho!'
  71. ]);
Advertisement
Add Comment
Please, Sign In to add comment