Challenge: Solution Review
This lesson will explain the solution to the problem from the previous coding challenge.
We'll cover the following...
Solution #
Press + to interact
class RockMusicVisitor{visit(musicLibrary) {var rockPlayList=[];var index = 0;var songlist = musicLibrary.songsList.lengthfor(var i=0; i<songlist; i++){var song = musicLibrary.songsList[i]if(song.getGenre() == "Rock"){rockPlayList[index] = song.getName()index++}}return rockPlayList}}class Song{constructor(name,genre){this.name = namethis.genre = genre}getName(){return this.name}getGenre(){return this.genre}}class MusicLibrary{constructor(){this.songsList = []}addSong(song){this.songsList.push(song)}accept(visitor){return visitor.visit(this)}}//creating a rock music visitorvar rockmusicVisitor = new RockMusicVisitor()//creating songs of different genresvar song1 = new Song("Bohemian Rhapsody","Rock")var song2 = new Song("Stairway to Heaven","Rock")var song3 = new Song("Oops I did it again", "Pop")var song4 = new Song("Crazy", "Country")//creating a music libraryvar musicLibrary = new MusicLibrary()//adding songs to the music librarymusicLibrary.addSong(song1)musicLibrary.addSong(song2)musicLibrary.addSong(song3)musicLibrary.addSong(song4)//using the rockmusicVisitor to create a separate rock music play listconsole.log("The music library has the following rock music: " + musicLibrary.accept(rockmusicVisitor))
Explanation
This challenge involved a music library containing different genres of music ...