Advertisement
Guest User

03. School Library

a guest
Feb 24th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function library(arr) {
  2.     let library = arr.shift().split("&");
  3.     let indexOfBook;
  4.     let indexOfSecondBook;
  5.  
  6.     for (let token of arr) {
  7.         if (token === "Done" || "") {
  8.             // do nothing
  9.         }
  10.  
  11.         token = token.split(" | ");
  12.         let action = token.shift();
  13.         let book = token.shift();
  14.  
  15.         if (action === "Add Book" && !check(book)) {
  16.             library.unshift(book)
  17.  
  18.         } else if (action === "Take Book" && check(book)) {
  19.             let indexOfBook = library.indexOf(book);
  20.             library.splice(indexOfBook, 1);
  21.  
  22.         } else if (action === "Swap Books" && check(book) && check(token[0])) {
  23.             let secondBook = token.shift();
  24.             indexOfBook = library.indexOf(book);
  25.             indexOfSecondBook = library.indexOf(secondBook);
  26.             library.splice(indexOfBook, 1, secondBook);
  27.             library.splice(indexOfSecondBook, 1, book);
  28.  
  29.         } else if (action === "Insert Book" && !check(book)) {
  30.             library.push(book);
  31.  
  32.         } else if (action === "Check Book" && 0 <= book && book < library.length) {
  33.             console.log(library[book]);
  34.  
  35.         }
  36.     }
  37.     return library.join(", ")
  38.     function check(checkedItem) {
  39.         if (library.includes(checkedItem)) {
  40.             return true;
  41.         } else {
  42.             return false;
  43.         }
  44.     }
  45. }
  46.  
  47. // console.log(library([
  48. //     'Don Quixote&The Great Gatsby&Moby Dick&Hamlet',
  49. //     'Add Book | The Odyssey',
  50. //     'Take Book | Don Quixote',
  51. //     "Insert Book | Alice's Adventures in Wonderland",
  52. //     'Check Book | 3',
  53. //     'Done',
  54. //     '',
  55. //     '',
  56. //     ''
  57. //   ]));
  58. // console.log(library([
  59. //     'Anna Karenina&Heart of Darkness&Catch-22& The Stranger',
  60. //     'Add Book | David Copperfield',
  61. //     'Add Book | One Thousand and One Nights',
  62. //     'Swap Books | One Thousand and One Nights | Catch-22',
  63. //     'Take Book | David Copperfield',
  64. //     'Insert Book | The Stories of Anton Chekhov',
  65. //     'Check Book | 17',
  66. //     'Done',
  67. //     ''
  68. //   ]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement