Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function manipulateArray(array, commands) {
- const add = (index, element) => {
- array.splice(index, 0, element);
- }
- const addMany = (inputOne, inputTwo) => {
- inputOne = Number(inputOne);
- inputTwo = inputTwo.map(Number);
- array.splice(inputOne, 0, ...inputTwo);
- }
- const contains = number => {
- if (array.includes(number)) {
- let index = array.indexOf(number);
- console.log(index);
- } else {
- console.log(-1);
- }
- }
- const remove = index => {
- array.splice(index, 1);
- }
- const shift = position => {
- for(let i = 0; i < position; i++) {
- array.push(array.shift());
- }
- }
- const sumPairs = () => {
- array = array.map((e, i, array) => i < array.length - 1 ? (array[i] += array[i + 1]) : array[i] = array[i]).filter((e, i) => i % 2 === 0);
- }
- for (let currentCommand of commands) {
- let wordsInCommand = currentCommand.split(' ');
- let firstWord = wordsInCommand.shift();
- if (firstWord == 'add') {
- let index = Number(wordsInCommand[0]);
- let element = Number(wordsInCommand[1]);
- add(index, element);
- } else if (firstWord == 'addMany') {
- let index = Number(wordsInCommand.shift());
- addMany(index, wordsInCommand);
- } else if (firstWord == 'contains') {
- let element = Number(wordsInCommand[0]);
- contains(element);
- } else if (firstWord == 'remove') {
- let index = Number(wordsInCommand[0]);
- remove(index);
- } else if (firstWord == 'shift') {
- let position = Number(wordsInCommand[0]);
- shift(position);
- } else if (firstWord == 'sumPairs') {
- sumPairs();
- } else if (firstWord == 'print'){
- array = array.join(', ');
- console.log(`[ ${array} ]`);
- break;
- }
- }
- }
Add Comment
Please, Sign In to add comment