I've been trying to compare all the series from my objects with the corresponding genre. I managed to display them but I'm practically writing the same code three times, while I'm sure there is a better way.
I'm trying to figure it out how to make the "type" argument match the right genre with the right series, so I don't have to call the same function three times. Maybe I shouldn't use objects into an Array, idk.
Please ask me if there is anything confusying.
'use strict';
//LIST OF SERIES
let listSeries =
[
{film: ['Breaking Bad', 'One of Us Is Lying'], genre: "Drama"},
{film: ['Servant', 'The Midnight Club'], genre: "Horror"},
{film: ['The Office US','Seinfeld'], genre: "Comedy"}
]
// SERIES CLASS
class Series
{
constructor(series, type)
{
this.series = series;
this.type = type;
}
}
//CLASS DISPLAY SERIES LIST WRTING HTML
class Display
{
tableBody = document.getElementById('tableBody');
add(libraryOfSeries)
{
let uiString = `<tr>
<td>${libraryOfSeries.series}</td>
<td >${libraryOfSeries.type}</td>
<button >Read!</button>
</tr>`;
tableBody.innerHTML = uiString;
}
}
// DISPLAY DRAMA SERIES AND CALLING THE ADD METHOD INTO THE CLASS DISPLAY
function displayDrama(series)
{
let dramaSeries = series.find(item => item.genre == "Drama");
for(let i of dramaSeries.film)
{
let currentSeries = new Series(i, dramaSeries.genre);
let display = new Display;
display.add(currentSeries)
}
}
displayDrama(allSeries);
// DISPLAY COMEDY SERIES AND CALLING THE ADD METHOD INTO THE CLASS DISPLAY
function displayComedy(series)
{
let comedySeries = series.find(item => item.genre == "Comedy");
for(let i of comedySeries.film)
{
let currentSeries = new Series(i, comedySeries.genre);
let display = new Display;
display.add(currentSeries)
}
}
displayComedy(allSeries);
// DISPLAY DRAMA SERIES AND CALLING THE ADD METHOD INTO THE CLASS DISPLAY
function displayHorror(series)
{
let horrorSeries = series.find(item => item.genre == "Horror");
for(let i of horrorSeries.film)
{
let currentSeries = new Series(i, horrorSeries.genre);
let display = new Display;
display.add(currentSeries)
}
}
displayHorror(allSeries);
CodePudding user response:
Just use a function with two input variables, then whenever you are trying to call that function, you can decide what you are going to filter.
function displayGenre(series, genreToFilter)
{
let comedySeries = series.find(item => item.genre === genreToFilter);
for(let i of comedySeries.film)
{
let currentSeries = new Series(i, comedySeries.genre);
let display = new Display;
display.add(currentSeries)
}
}
// Calling the function to display drama:
displayGenre(allSeries, "Drama")
// Calling the function to display comedy:
displayGenre(allSeries, "Comedy")
// Calling the function to display horror:
displayGenre(allSeries, "Horror")
Then you can use type
variable in the function as well.