Liliana797979

array manipulations - fundamentals

Aug 22nd, 2021
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.      
  3. function solve(commands){
  4.     let arr = commands
  5.     .shift()
  6.     .split(' ')
  7.     .map(Number);
  8.     for(let i = 0;i<commands.length;i++){ // въртим по броя на командите
  9.         let [command,firstNum, secondNum]=commands[i].split(' '); // взимаме съответната команда, число и индекс. П.С. Първо бих взела само командата и само, когато тя е insert ще взимам secondNum(който реално е индекса)
  10.         firstNum = Number(firstNum);
  11.         secondNum = Number(secondNum);
  12.  
  13.    
  14.     switch(command){
  15.         case "Add":
  16.             add(firstNum); // подаваме параметър
  17.             break;
  18.             case "Remove":
  19.                 remove(firstNum); // подаваме параметър
  20.                 break;
  21.                 case "RemoveAt":
  22.                         removeAt(firstNum); //подаваме параметър
  23.                     break;
  24.                     case "Insert":
  25.                     insert(firstNum, secondNum); // подаваме параметри
  26.                         break;
  27.     }
  28. }
  29.     function add(el){
  30.         arr.push(el)
  31.         }
  32.         function remove(num){
  33.             arr=arr.filter(el=>el!==num);
  34.         }
  35.         function removeAt(index){
  36.             arr.splice(index,1);
  37.         }
  38.         function insert(num,index){
  39.             arr.splice(index,0,num);
  40.         }
  41.         console.log(arr.join(' '))
  42. }
  43.  
  44. solve([ '4 19 2 53 6 43', 'Add 3', 'Remove 2', 'RemoveAt 1', 'Insert 8 3' ])
Advertisement
Add Comment
Please, Sign In to add comment