Liliana797979

Problem 2_5 mid exam

Aug 15th, 2021
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function cards(input) {
  2.   const [list, ...commands] = input;
  3.   const deck = list.split(":");
  4.   const result = commands.reduce((acc, curr) => {
  5.     const [comm, name, name2] = curr.split(" ");
  6.     if (comm === "Ready") {
  7.       return acc;
  8.     }
  9.     if (comm === "Add") {
  10.         const index = deck.indexOf(name)
  11.         if(index === -1){
  12.             console.log("Card not found.")
  13.             return acc;
  14.         }
  15.  
  16.         return [...acc, name]
  17.     }
  18.  
  19.     if (comm === "Insert") {
  20.         const insertIndex = Number(name2)
  21.         const index = deck.indexOf(name)
  22.         if (index === -1 || (acc.length >= insertIndex && insertIndex < 0)){
  23.             console.log("Error!");
  24.             return acc;
  25.         }
  26.         return [...acc.slice(0,insertIndex), name, ...acc.slice(insertIndex)]
  27.     }
  28.     if (comm === "Remove") {
  29.         const index = acc.indexOf(name)
  30.         if(index === -1){
  31.             console.log("Card not found.")
  32.             return acc;
  33.         }
  34.  
  35.         return [...acc.slice(0, index), ...acc.slice(index + 1)];
  36.     }
  37.     if (comm === "Swap") {
  38.         const index = acc.indexOf(name)
  39.         const index2 = acc.indexOf(name2)
  40.  
  41.         const first = acc[index]
  42.         const second = acc[index2]
  43.  
  44.         acc[index] = second
  45.         acc[index2] = first
  46.        
  47.         return acc
  48.     }
  49.     if (comm === "Shuffle") {
  50.      
  51.       const rev = acc.reverse();
  52.       return rev
  53.     }
  54.   }, []);
  55.  
  56.   console.log(result.join(' '));
  57. }
  58.  
  59. cards([
  60.   "Innervate:Moonfire:Pounce:Claw:Wrath:Bite",
  61.   "Add Moonfire",
  62.   "Add Pounce",
  63.   "Add Bite",
  64.   "Add Wrath",
  65.   "Insert Claw 0",
  66.   "Swap Claw Moonfire",
  67.   "Remove Bite",
  68.   "Shuffle deck",
  69.   "Ready",
  70. ]);
Advertisement
Add Comment
Please, Sign In to add comment