Advertisement
AlexzanderF

Array Manipulator

Jun 26th, 2020
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function arrayManipulator(array, manipulations) {
  2.     for (let i = 0; i < manipulations.length; i++) {
  3.         let manipulation = manipulations[i].split(" ");
  4.         let command = manipulation.shift();
  5.         let firstNum = Number(manipulation.shift());
  6.         let secNum = Number(manipulation[0]);
  7.  
  8.         switch (command) {
  9.             case "add":
  10.                 array.splice(firstNum, 0, secNum);
  11.                 break;
  12.  
  13.             case "addMany":
  14.                 let index = firstNum;
  15.                 for (let j = 0; j < manipulation.length; j++) {
  16.                     array.splice(index + j, 0, Number(manipulation[j]));
  17.                 }
  18.                 break;
  19.  
  20.             case "contains":
  21.                 if (array.includes(firstNum)) {
  22.                     console.log(array.indexOf(firstNum));
  23.                 } else {
  24.                     console.log(-1);
  25.                 }
  26.                 break;
  27.  
  28.             case "remove":
  29.                 array.splice(firstNum, 1);
  30.                 break;
  31.  
  32.             case "shift":
  33.                 let positions = firstNum;
  34.                 let shifted = array.splice(0, positions);
  35.                 for (let j = 0; j < shifted.length; j++) {
  36.                     array.push(shifted[j]);
  37.                 }
  38.                 break;
  39.             case "sumPairs":
  40.                 let sumArr = [];
  41.                 for (let j = 0; j < array.length; j += 2) {
  42.                     if (j + 1 > array.length - 1) {
  43.                         sumArr.push(array[j] + 0);
  44.                     } else {
  45.                         sumArr.push(array[j] + array[j + 1]);
  46.                     }
  47.                 }
  48.                 let sliced = sumArr.slice(0);
  49.                 array = sliced;
  50.                 break;
  51.             case "print":
  52.                 console.log(`[ ${array.join(", ")} ]`);
  53.                 break;
  54.         }
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement