SKGreyHound

08. Array Manipulator

Jun 29th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. function arrayManipulator(arr, inputCommands) {
  2.  
  3. let commands = inputCommands.shift().split(' ');
  4.  
  5. while (commands[0] !== 'print') {
  6. let currCommand = commands[0];
  7.  
  8. switch (currCommand) {
  9. case 'add': arr.splice(commands[1], 0, Number(commands[2]));
  10. break;
  11. case 'addMany':
  12. commands.shift();
  13. let elements = commands.map(Number);
  14. let index = elements.shift();
  15. addMany(index, elements, arr);
  16. break;
  17. case 'contains': console.log(contains(Number(commands[1])));
  18. break;
  19. case 'remove': arr.splice(Number(commands[1]), 1);
  20. break;
  21. case 'shift': arr = shift(Number(commands[1]), arr);
  22. break;
  23. case 'sumPairs':
  24. arr = sumPairs(arr);
  25. break;
  26. }
  27.  
  28. commands = inputCommands.shift().split(' ')
  29. }
  30. console.log(`[ ${arr.join(', ')} ]`);
  31.  
  32. function contains(trgNum) {
  33. let isFound = false;
  34. for (let i = 0; i < arr.length; i++) {
  35. if (arr[i] === Number(trgNum)) {
  36. isFound = true;
  37. }
  38. }
  39. if (isFound) {
  40. return 0;
  41. } else {
  42. return -1;
  43. }
  44. }
  45.  
  46. function shift(rotations, array) {
  47. let realRotations = rotations % array.length;
  48. let result = [];
  49.  
  50. for (let i = 0; i < array.length; i++) {
  51. let currentElement = array[i];
  52.  
  53. if (i >= realRotations) {
  54. result.push(currentElement);
  55. }
  56. }
  57.  
  58. for (let j = 0; j < array.length; j++) {
  59. let currentElement = array[j];
  60.  
  61. if (j < realRotations) {
  62. result.push(currentElement);
  63. } else {
  64. break;
  65. }
  66. }
  67.  
  68. return result;
  69. }
  70.  
  71. function addMany(index, elements, arr) {
  72. for (let element of elements) {
  73. arr.splice(index, 0, element);
  74. index++;
  75. }
  76. }
  77.  
  78. function sumPairs(array) {
  79. let result = [];
  80.  
  81. for (let i = 0; i < array.length; i += 2) {
  82. let currentElement = array[i];
  83. let nextElement = array[i + 1];
  84. let currentSum = currentElement + nextElement;
  85. if (nextElement !== undefined) {
  86. result.push(currentSum);
  87. } else {
  88. result.push(currentElement);
  89. }
  90. }
  91.  
  92. return result;
  93. }
  94. }
Add Comment
Please, Sign In to add comment