vikkktor

Arrays_add_and_remove

Oct 13th, 2021
872
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //-------------------------------------------------------------------------------------
  2. //Write a function that adds and removes numbers to/from an array.
  3. //You will receive a command which can either be "add" or "remove".
  4. //The initial number is 1. Each input command should increase that number, regardless of what it is.
  5. //•   Upon receiving an "add" command you should add the current number to your array.
  6. //•    Upon receiving the "remove" command you should remove the last entered number, currently existent in the array.
  7. // --- Input
  8. //The input comes as array of strings. Each element holds a command.
  9. //-------------------------------------------------------------------------------------
  10. function add_and_remove(commands) {
  11.     let commandsL = commands.length;
  12.  
  13.     let endArray = [];
  14.     let currentNum = 1;
  15.     for (let i = 0; i < commandsL; i++) {
  16.         if (commands[i] == "add") {
  17.             endArray.push(currentNum);
  18.         } else if (commands[i] == "remove") {
  19.             endArray.pop()
  20.         }
  21.         currentNum += 1;
  22.     }
  23.     if (endArray.length > 0) {
  24.         console.log(endArray.join(' '));
  25.     } else {
  26.         console.log("Empty");
  27.     }
  28. }
RAW Paste Data