dddilian

01. World Tour FINAL EXAM JS

Aug 9th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(inputArr) { //100т.
  2.     let str = inputArr.shift();
  3.  
  4.  
  5.     for (const line of inputArr) {
  6.  
  7.         if (line === "Travel") {
  8.             console.log(`Ready for world tour! Planned stops: ${str}`)
  9.             break;
  10.  
  11.         } else {
  12.             let tokens = line.split(":");
  13.  
  14.             if (line.includes("Add Stop")) { //Add Stop:{index}:{string} – insert the given string at that index only if the index is valid
  15.                 let idx = Number(tokens[1]);
  16.                 let newStop = tokens[2];
  17.                 // console.log(newStop)
  18.                 if (idx >= 0 && idx <= str.length - 1) { //ако е валиден индекса
  19.                     str = str.slice(0, idx) + newStop + str.slice(idx);
  20.                     //console.log(str);
  21.                 }
  22.                 console.log(str);
  23.  
  24.  
  25.             } else if (line.includes("Remove Stop")) { //Remove Stop:{start_index}:{end_index} – remove the elements of the string from the starting
  26.                 let startIdx = Number(tokens[1]);
  27.                 let endIdx = Number(tokens[2]);
  28.                 if (startIdx >= 0 && startIdx <= str.length - 1 && endIdx >= 0 && endIdx <= str.length - 1) {
  29.                     let strToRemove = str.substring(startIdx, endIdx + 1);
  30.                     str = str.replace(strToRemove, "");
  31.  
  32.                 }
  33.                 console.log(str)
  34.  
  35.  
  36.             } else if (line.includes("Switch")) { //Switch:{old_string}:{new_string} – if the old string is in the initial string, replace it with the new one. (all occurrences)
  37.                 let oldStr = tokens[1];
  38.                 let newStr = tokens[2];
  39.                 if (str.includes(oldStr)) {
  40.                     str = str.split(oldStr).join(newStr);
  41.                     //console.log(str);
  42.                 }
  43.                 console.log(str); //или може би тук трябва да се принтне, а не горе в if-а
  44.             }
  45.         }
  46.     }
  47. }
  48.  
  49.  
  50. solve(['Hawai::Cyprys-Greece', 'Add Stop:7:Rome', 'Remove Stop:11:16', 'Switch:Hawai:Bulgaria', 'Travel']);
Add Comment
Please, Sign In to add comment