Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function arrayManipulator(arr, inputCommands) {
- let commands = inputCommands.shift().split(' ');
- while (commands[0] !== 'print') {
- let currCommand = commands[0];
- switch (currCommand) {
- case 'add': arr.splice(commands[1], 0, Number(commands[2]));
- break;
- case 'addMany':
- commands.shift();
- let elements = commands.map(Number);
- let index = elements.shift();
- addMany(index, elements, arr);
- break;
- case 'contains': console.log(contains(Number(commands[1])));
- break;
- case 'remove': arr.splice(Number(commands[1]), 1);
- break;
- case 'shift': arr = shift(Number(commands[1]), arr);
- break;
- case 'sumPairs':
- arr = sumPairs(arr);
- break;
- }
- commands = inputCommands.shift().split(' ')
- }
- console.log(`[ ${arr.join(', ')} ]`);
- function contains(trgNum) {
- let isFound = false;
- for (let i = 0; i < arr.length; i++) {
- if (arr[i] === Number(trgNum)) {
- isFound = true;
- }
- }
- if (isFound) {
- return 0;
- } else {
- return -1;
- }
- }
- function shift(rotations, array) {
- let realRotations = rotations % array.length;
- let result = [];
- for (let i = 0; i < array.length; i++) {
- let currentElement = array[i];
- if (i >= realRotations) {
- result.push(currentElement);
- }
- }
- for (let j = 0; j < array.length; j++) {
- let currentElement = array[j];
- if (j < realRotations) {
- result.push(currentElement);
- } else {
- break;
- }
- }
- return result;
- }
- function addMany(index, elements, arr) {
- for (let element of elements) {
- arr.splice(index, 0, element);
- index++;
- }
- }
- function sumPairs(array) {
- let result = [];
- for (let i = 0; i < array.length; i += 2) {
- let currentElement = array[i];
- let nextElement = array[i + 1];
- let currentSum = currentElement + nextElement;
- if (nextElement !== undefined) {
- result.push(currentSum);
- } else {
- result.push(currentElement);
- }
- }
- return result;
- }
- }
Add Comment
Please, Sign In to add comment