krasizorbov

Book Shelf

Jul 8th, 2020
1,233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solution(input = []) {
  2.   let data = new Map();
  3.   let genres = {};
  4.   for (let i = 0; i < input.length; i++) {
  5.     if (input[i].includes("->")) {
  6.       let [id, genre] = input[i].split(" -> ");
  7.       if (!data.has(id)) {
  8.         genres[genre] = id;
  9.         genre = [];
  10.         data.set(id, genre);
  11.       }
  12.     } else {
  13.       let line = input[i].split(": ");
  14.       let bookName = line[0];
  15.       let [authorName, genre] = line[1].split(", ");
  16.       if (genres.hasOwnProperty(genre)) {
  17.         let id = genres[genre];
  18.         let obj = { title: bookName, author: authorName, genre: genre };
  19.         data.get(id).push(obj);
  20.       }
  21.     }
  22.   }
  23.   data = new Map([...data.entries()].sort((a, b) => b[1].length - a[1].length));
  24.   for (const entries of data) {
  25.     console.log(`${entries[0]} ${entries[1][0].genre}: ${entries[1].length}`);
  26.     entries[1].sort((a, b) => a.title.localeCompare(b.title));
  27.     for (const obj of entries[1]) {
  28.       console.log(`--> ${obj.title}: ${obj.author}`);
  29.     }
  30.   }
  31. }
  32. solution([
  33.   "1 -> history",
  34.   "1 -> action",
  35.   "Death in Time: Criss Bell, mystery",
  36.   "2 -> mystery",
  37.   "3 -> sci-fi",
  38.   "Child of Silver: Bruce Rich, mystery",
  39.   "Hurting Secrets: Dustin Bolt, action",
  40.   "Future of Dawn: Aiden Rose, sci-fi",
  41.   "Lions and Rats: Gabe Roads, history",
  42.   "2 -> romance",
  43.   "Effect of the Void: Shay B, romance",
  44.   "Losing Dreams: Gail Starr, sci-fi",
  45.   "Name of Earth: Jo Bell, sci-fi",
  46.   "Pilots of Stone: Brook Jay, history",
  47. ]);
Advertisement
Add Comment
Please, Sign In to add comment