nikolayneykov

Untitled

Feb 23rd, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function manipulateArray(arr, commands) {
  2.  
  3.     for (let c of commands) {
  4.         let tokens = c.split(' ');
  5.         let command = tokens[0];
  6.  
  7.         if (command === 'add') {
  8.             let index = Number(tokens[1]);
  9.             let element = Number(tokens[2]);
  10.             arr.splice(index, 0, element);
  11.         } else if (command === 'addMany') {
  12.             let index = Number(tokens[1]);
  13.             let elements = tokens.slice(2).map(Number);
  14.             arr.splice(index, 0, ...elements);
  15.         } else if (command === 'contains') {
  16.             let element = Number(tokens[1]);
  17.             console.log(arr.indexOf(element));
  18.         } else if (command === 'remove') {
  19.             let index = Number(tokens[1]);
  20.             arr.splice(index, 1);
  21.         } else if (command === 'shift') {
  22.             let positions = Number(tokens[1]);
  23.             while (positions > 0) {
  24.                 arr.push(arr.shift());
  25.                 positions--;
  26.             }
  27.         } else if (command === 'sumPairs') {
  28.             arr = arr
  29.                 .map((e, i, arr) => (i < arr.length - 1) ? (arr[i] += arr[i + 1]) : (arr[i] = arr[i]))
  30.                 .filter((e, i) => i % 2 === 0);
  31.  
  32.         } else if (command === 'print') {
  33.             break;
  34.         }
  35.     }
  36.  
  37.     console.log(arr);
  38. }
Advertisement
Add Comment
Please, Sign In to add comment