Advertisement
Guest User

arrayManipulator

a guest
Apr 9th, 2020
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function arrayManipulator(array,comands) {
  2.  
  3.  
  4.  
  5.     for(let i=0;i<comands.length;i++) {
  6.         let action = comands[i].split(` `);
  7.        
  8.        
  9.        if(action[0] === `add`) {
  10.            action.shift();
  11.         array = add(array,action)
  12.        } else if( action[0] === `contains`) {
  13.         action.shift();
  14.         console.log(array.indexOf(Number(action[0])))
  15.        } else if(action[0]=== `addMany`) {
  16.         action.shift();
  17.         array = addMany(array,action)
  18.        } else if( action[0] === `remove`) {
  19.         action.shift();
  20.         array = remove(array,action);
  21.        } else if(action[0] === `shift`) {
  22.         action.shift();
  23.         array = shft(array,action);
  24.        } else if(action[0] === `sumPairs`) {
  25.        
  26.         array = sumPair(array);
  27.        } else if(action[0] === `print`) {
  28.        
  29.         break;
  30.        }                            
  31.              
  32.        
  33.     }
  34.  
  35.     return `[ ${array.join(`, `)} ]`
  36.  
  37.     function add(arr,action) {
  38.        
  39.         arr.splice(action[0],0,Number(action[1]))
  40.         return arr;
  41.  
  42.     }
  43.  
  44.  
  45.     function addMany(arr,action) {
  46.  
  47.       let  index = action.shift()
  48.        
  49.         for(let i=0;i<action.length;i++) {
  50.             arr.splice(index++,0,Number(action[i]))
  51.         }
  52.         return arr;
  53.    
  54.        
  55.        
  56.  
  57.        
  58.     }
  59.  
  60.     function remove(arr,action) {
  61.        let  index = action[0]
  62.         arr.splice(Number(index),1)
  63.         return arr;
  64.     }
  65.  
  66.     function shft(arr,index) {
  67.  
  68.         for(let i=0;i<index;i++) {
  69.             arr.push(arr[i]);
  70.             arr.shift(arr[i]);
  71.            
  72.         }
  73.  
  74.         return arr
  75.     }
  76.  
  77.     function sumPair(arr) {
  78.         let output = []
  79.        while(arr.length>0) {
  80.            let a = arr.shift() || 0;
  81.            let b = arr.shift() || 0;
  82.            output.push(a+b)
  83.        }
  84.        return output;
  85.         }
  86.        
  87.  
  88.  
  89. }
  90. arrayManipulator([1, 2, 3, 4, 5],[`addMany 5 9 8 7 6 5`,`contains 15`,`remove 3`,`shift 1`,`print`]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement