Advertisement
drak138

arrayManipulator with switch

Feb 9th, 2024
1,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function arrManipulator(arr,elements){
  2.     for(let row of elements){
  3.         row=row.split(" ")
  4.         let command=row.shift()
  5.         let firstNum=Number(row.shift())
  6.         if(command!=='print'){
  7.             switch(command){
  8.                 case "add":
  9.                     add(arr,firstNum,row)
  10.                 break;
  11.                 case "remove":
  12.                     remove(arr,firstNum)
  13.                 break;
  14.                 case "addMany":
  15.                     addMany(arr,firstNum,row)
  16.                 break;
  17.                 case "contains":
  18.                     contains(arr,firstNum)
  19.                 break;
  20.                 case "shift":
  21.                     shift(arr,firstNum)
  22.                 break;
  23.                 case "sumPairs":
  24.                     arr=sumPair(arr,)
  25.                 break;
  26.             }
  27.         }
  28.         else{
  29.             break;
  30.         }
  31.     }
  32.     console.log(`[ ${arr.join(", ")} ]`)
  33.  
  34.     function add(arr,index,element){
  35.        return arr.splice(index,0,Number(element))
  36.     }
  37.  
  38.     function remove(arr,index){
  39.        return arr.splice(index,1)
  40.     }
  41.  
  42.     function addMany(arr,index,row){
  43.         row=row.toString().split(",")
  44.         for(let num of row.reverse()){
  45.             arr.splice(index,0,Number(num))
  46.         }
  47.     }
  48.  
  49.     function contains(arr,searchedNum){
  50.         if(arr.includes(searchedNum)){
  51.             console.log(arr.indexOf(searchedNum))
  52.         }
  53.         else{
  54.             console.log(-1)
  55.         }
  56.     }
  57.  
  58.     function shift(arr,count){
  59.         for(let i=0;i<count;i++){
  60.             arr.push(arr.shift())
  61.         }
  62.     }
  63.  
  64.     function sumPair(arr){
  65.         let sum=[]
  66.         if(arr.length%2!==0){
  67.             arr.push(0)
  68.         }
  69.         while(arr.length>0){
  70.             let firstPair=arr.shift()
  71.             let secondPair=arr.shift()
  72.             sum.push(firstPair+secondPair)
  73.         }
  74.         return sum
  75.     }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement