Advertisement
Lulunga

mid exam 03. Easter Shopping

Jun 29th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let shopList = input.shift().split(' ');
  3.     let numberOfCommands = Number(input.shift());
  4.     let commands = input;
  5.     for (let line of input) {
  6.         let tokens = line.split(' ');
  7.         let command = tokens[0];
  8.         if (command === 'Include') {
  9.             shopList.push(tokens[1]);
  10.         } else if (command === 'Visit') {
  11.             let numberOfShops = Number(tokens[2]);
  12.             if (numberOfShops <= shopList.length) {
  13.                 if (tokens[1] === 'first') {
  14.                     shopList.splice(0, numberOfShops);
  15.                 } else if (tokens[1] === 'last') {
  16.                     shopList.splice(shopList.length - numberOfShops, numberOfShops);
  17.                 }
  18.             }
  19.         } else if (command === 'Prefer') {
  20.             let firstIndex = Number(tokens[1]);
  21.             let secondIndex = Number(tokens[2]);
  22.             if ((firstIndex >= 0 && firstIndex < shopList.length) && (secondIndex >= 0 && secondIndex < shopList.length)) {
  23.                 let firstShop = shopList[firstIndex];
  24.                 let secondShop = shopList[secondIndex];
  25.                 shopList[firstIndex] = secondShop;
  26.                 shopList[secondIndex] = firstShop;
  27.             }
  28.         } else if (command === 'Place') {
  29.             let index = Number(tokens[2]) + 1;
  30.             let shop = tokens[1];
  31.             if (index >= 0 && index <= shopList.length) {
  32.                 shopList.splice(index, 0, shop);
  33.             }
  34.         }
  35.     }
  36.     console.log(`Shops left:\n${shopList.join(' ')}`);
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement