Guest User

Untitled

a guest
Jun 25th, 2019
126
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // The final quest
  3. function final(input) {
  4.  
  5.     let sentence = input.shift().split(" ");
  6.  
  7.     for (let i = 0; i < input.length; i++) {
  8.         let cmd = input[i].split(" ")[0];
  9.         let wordOne = input[i].split(" ")[1];
  10.         let wordTwo = input[i].split(" ")[2];
  11.         if (cmd === "Delete") {
  12.             //Delete {index} – removes the word after the given index if it is valid.
  13.             if (typeof sentence[wordOne] !== "undefined") {
  14.                 let index = +wordOne + 1;
  15.                 sentence.splice(index, 1);
  16.             }
  17.         } else if (cmd === "Swap") {
  18.             //Swap {word1} {word2} – find the given words in the collections if they exist and swap their places.
  19.             if(sentence.includes(wordOne) && sentence.includes(wordTwo)) {
  20.                let indexOfWordOne = sentence.indexOf(wordOne);
  21.                let indexOfWordTwo = sentence.indexOf(wordTwo);
  22.                sentence.splice(indexOfWordOne, 1, wordTwo);
  23.                sentence.splice(indexOfWordTwo, 1, wordOne);
  24.             }
  25.         } else if (cmd === "Put") {
  26.             //Put {word} {index} – add a word at the previous place {index} before the given one, if it exists.
  27.             if (typeof sentence[wordTwo] !== "undefined") {
  28.                let index = +wordTwo - 1;
  29.                sentence.splice(index, 0, wordOne);
  30.             }
  31.         } else if (cmd === "Sort") {
  32.             //Sort – you must sort the words in descending order
  33.             sentence.sort(function(a, b) {
  34.                 return b.localeCompare(a)
  35.             });
  36.         } else if (cmd === "Replace") {
  37.             //Replace {word1} {word2} – find the second word {word2} in the collection (if it exists) and replace it with the first word – {word1}.
  38.             if(sentence.includes(wordTwo)) {
  39.                 sentence.splice(sentence.indexOf(wordTwo), 1, wordOne);
  40.             }
  41.         } else {
  42.            break;
  43.         }
  44.     }
  45.     return(sentence.join(" "));
  46. }
  47. console.log(final([`Congratulations! You last also through the have challenge!`,
  48.     `Swap have last`,
  49.     `Replace made have`,
  50.     `Delete 2`,
  51.     `Put it 4`,
  52.     `Stop`]));
RAW Paste Data