Advertisement
Todorov_Stanimir

04. Movies Objects and Classes - Exercise

Dec 17th, 2020 (edited)
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function movies(input) {
  2.   moviesSheet = new Map();
  3.  
  4.   const propertiesMapper = {
  5.     onDate: "date",
  6.     directedBy: "director",
  7.   };
  8.  
  9.   function findComand(commandLine) {
  10.     return commandLine.startsWith("addMovie") ? "addMovie" : "addPropertyToMovie";
  11.   };
  12.  
  13.   const actions = {
  14.     split: function(string,key) {
  15.       return string.split(key).map(e => e.trim());
  16.     },
  17.     addMovie: function(commanLine) {
  18.       const [_, movieName] = this.split(commanLine, "addMovie");
  19.       if (!moviesSheet.has(movieName))
  20.         moviesSheet.set(movieName, {});
  21.     },
  22.     addPropertyToMovie: function(commanLine) {
  23.       Object.keys(propertiesMapper).map((key) => {
  24.         if (commanLine.includes(key)) {
  25.           const [movieName, propertyValue] = this.split(commanLine, key);
  26.           const movie = moviesSheet.get(movieName);
  27.  
  28.           if (movie) {
  29.             const property = propertiesMapper[key];
  30.             movie[property] = propertyValue;
  31.           }
  32.         }
  33.       });
  34.     }
  35.   };
  36.  
  37.   input.map((commandLine) => {
  38.     actions[findComand(commandLine)](commandLine);
  39.   });
  40.  
  41.   for (let [key, value] of moviesSheet) {
  42.     if (Object.keys(value).length === Object.keys(propertiesMapper).length) {
  43.       console.log(JSON.stringify({ name: key, ...value }));
  44.     }
  45.   }
  46. }
  47.  
  48. movies([
  49.   "addMovie Fast and Furious",
  50.   "addMovie Godfather",
  51.   "Inception directedBy Christopher Nolan",
  52.   "Godfather directedBy Francis Ford Coppola",
  53.   "Godfather onDate 29.07.2018",
  54.   "Fast and Furious onDate 30.07.2018",
  55.   "Batman onDate 01.08.2018",
  56.   "Fast and Furious directedBy Rob Cohen",
  57. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement