Liliana797979

book shelf - fundamentals

Jul 23rd, 2021
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.      
  2. function bookShelf(input) {
  3.   let shelvesList = new Map();
  4.   let bookList = new Map();
  5.   for (const line of input) {
  6.     if (line.includes(" -> ")) {
  7.       let [id, type] = line.split(" -> ");
  8.       if (!shelvesList.has(type)) {
  9.         let temp = [...shelvesList.values()];
  10.         if (!temp.includes(id)) {
  11.           shelvesList.set(type, id);
  12.         }
  13.       }
  14.     } else if (line.includes(": ")) {
  15.       let [bookTitle, rest] = line.split(": ");
  16.       let [bookAuthor, genre] = rest.split(", ");
  17.       let curShelves = [...shelvesList.keys()];
  18.       if (curShelves.includes(genre)) {
  19.         if (!bookList.has(genre)) {
  20.           bookList.set(genre, [
  21.             { bookTitle: bookTitle, bookAuthor: bookAuthor },
  22.           ]);
  23.         } else {
  24.           let currBookList = bookList.get(genre);
  25.           currBookList.push({ bookTitle: bookTitle, bookAuthor: bookAuthor });
  26.           bookList.set(genre, currBookList);
  27.         }
  28.       }
  29.     }
  30.   }
  31.  
  32.   [...bookList.entries()]
  33.     .sort((a, b) => b[1].length - a[1].length)
  34.     .forEach((shelf) => {
  35.       let [genre, books] = shelf;
  36.       books.sort((a, b) => a.bookTitle.localeCompare(b.bookTitle));
  37.       console.log(`${shelvesList.get(genre)} ${genre}: ${books.length}`);
  38.       for (const book of books) {
  39.         console.log(`--> ${book.bookTitle}: ${book.bookAuthor}`);
  40.       }
  41.     });
  42. }
Advertisement
Add Comment
Please, Sign In to add comment