Liliana797979

problem 2_1 - mid exam

Jul 22nd, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.      
  3. function groceryStore(input) {
  4.   let list = input.shift().split('|');
  5.  
  6.   let end = false;
  7.   for (let i = 0; i < input.length; i++) {
  8.     let splitCommand = input[i].split('%');
  9.     let command = splitCommand.shift();
  10.     let items = splitCommand;
  11.     let item = items.shift();
  12.  
  13.     switch (command) {
  14.       case "Important":
  15.         if (list.includes(item)) {
  16.           list.splice(list.indexOf(item), 1);
  17.           list.unshift(item)
  18.         } else {
  19.           list.splice(0, 0, item)
  20.         }
  21.         break;
  22.       case "Add":
  23.         if (!list.includes(item)) {
  24.           list.push(item);
  25.         } else {
  26.           console.log(`The product is already in the list.`)
  27.         }
  28.         break;
  29.       case "Swap":
  30.         let itemTwo = items.shift();
  31.         let itemOneMissing = !list.includes(item);
  32.         let itemTwoMissing = !list.includes(itemTwo);
  33.         let itemOneIndex = list.indexOf(item);
  34.         let itemTwoIndex = list.indexOf(itemTwo);
  35.         if (list.includes(item) && list.includes(itemTwo)) {
  36.           list.splice(itemOneIndex, 1, itemTwo);
  37.           list.splice(itemTwoIndex, 1, item);
  38.         } else {
  39.           let missing = itemOneMissing ? item : itemTwo;
  40.           console.log(`Product ${missing} missing!`)
  41.         }
  42.         break;
  43.       case "Remove":
  44.         if (list.includes(item)) {
  45.           let itemIndex = list.indexOf(item);
  46.           list.splice(itemIndex)
  47.         } else {
  48.           console.log(`Product ${item} isn't in the list.`)
  49.        }
  50.        break;
  51.      case "Reversed":
  52.        list.reverse()
  53.        break;
  54.      case "Shop!":
  55.        end = true;
  56.        break;
  57.      default:
  58.        break;
  59.    }
  60.    if(end) { break; }
  61.  }
  62.  
  63.  list.map((item, index) => console.log(`${index + 1}. ${item}`))
  64. }
Advertisement
Add Comment
Please, Sign In to add comment