Liliana797979

array manipulator - fundamentals

Jun 24th, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.      
  2. function solve3(arr, commands) {
  3.     let newArr = [];
  4.     for (let el of commands) {
  5.         let [command, index, element] = el.split(' ');
  6.         switch (command) {
  7.             case 'add':
  8.                 arr.splice(index, 0, +element);
  9.                 break;
  10.             case 'addMany':
  11.                 let currentEl = 0;
  12.                 let removeFirst = el.split(' ');
  13.                 for (let i = removeFirst.length - 1; i >= 2; i--) {
  14.                     currentEl = removeFirst[i];
  15.                     arr.splice(index, 0, +currentEl);
  16.                 }
  17.                 break;
  18.             case 'contains':
  19.                 // if (arr.indexOf(+index) !== -1) {
  20.                 //     console.log('0');
  21.                 // } else {
  22.                 //     console.log('-1');
  23.                 // }
  24.                 console.log(arr.indexOf(+index));
  25.                 break;
  26.             case 'remove':
  27.                 arr.splice(index, 1);
  28.                 break;
  29.             case 'shift':
  30.                 let position = +index;
  31.                 for (let i = 0; i < position; i++) {
  32.                     let firstEl = arr.shift();
  33.                     arr.push(firstEl);
  34.                 }
  35.                 break;
  36.             case 'sumPairs':
  37.                 // if (arr.length % 2 === 0) {
  38.                     let els = arr.reduce(function(total, el, index) {
  39.                         if (index % 2 === 0) {
  40.                             total.push(+arr[index] + (+arr[index + 1] || 0));
  41.                         }
  42.                         return total;
  43.                     }, []);
  44.                     arr = els;
  45.                 // }
  46.                 break;
  47.             case 'print':
  48.                 for (let el of arr) {
  49.                     newArr.push(el);
  50.                 }
  51.                 break;
  52.         }
  53.     }
  54.     // console.log(newArr);
  55.     console.log('[ ' + newArr.join(', ') + ' ]');
  56. }
Advertisement
Add Comment
Please, Sign In to add comment