georgiev955

02. Shopping List

Jun 2nd, 2023
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function shoppingList(inputArray) {
  2.   let productsArray = inputArray[0].split("!");
  3.   let index = 1;
  4.   let command;
  5.  
  6.   while ((command = inputArray[index]) !== "Go Shopping!") {
  7.     let commandArray = command.split(" ");
  8.     let action = commandArray[0];
  9.     let item = commandArray[1];
  10.     let newItem = commandArray[2];
  11.  
  12.     switch (action) {
  13.       case "Urgent":
  14.         urgent(item);
  15.         break;
  16.       case "Unnecessary":
  17.         unnecessary(item);
  18.         break;
  19.       case "Correct":
  20.         correct(item, newItem);
  21.         break;
  22.       case "Rearrange":
  23.         rearrange(item);
  24.         break;
  25.     }
  26.  
  27.     function urgent(item) {
  28.       if (!productsArray.includes(item)) {
  29.         productsArray.unshift(item);
  30.       }
  31.     }
  32.  
  33.     function unnecessary(item) {
  34.       if (productsArray.includes(item)) {
  35.         let indexToRemove = productsArray.indexOf(item);
  36.         productsArray.splice(indexToRemove, 1);
  37.       }
  38.     }
  39.  
  40.     function correct(item, newItem) {
  41.       if (productsArray.includes(item)) {
  42.         let indexToRename = productsArray.indexOf(item);
  43.         productsArray[indexToRename] = newItem;
  44.       }
  45.     }
  46.  
  47.     function rearrange(item) {
  48.       if (productsArray.includes(item)) {
  49.         let indexToMove = productsArray.indexOf(item);
  50.         let itemToMove = productsArray.splice(indexToMove, 1).join('');
  51.         productsArray.push(itemToMove);
  52.       }
  53.     }
  54.  
  55.     index++;
  56.     }
  57.     console.log(productsArray.join(', '))
  58. }
Advertisement
Add Comment
Please, Sign In to add comment