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.length
for(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 = name
this.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 visitor
var rockmusicVisitor = new RockMusicVisitor()
//creating songs of different genres
var 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 library
var musicLibrary = new MusicLibrary()
//adding songs to the music library
musicLibrary.addSong(song1)
musicLibrary.addSong(song2)
musicLibrary.addSong(song3)
musicLibrary.addSong(song4)
//using the rockmusicVisitor to create a separate rock music play list
console.log("The music library has the following rock music: " + musicLibrary.accept(rockmusicVisitor))

Explanation

This challenge involved a music library containing different genres of music ...