In: Computer Science
In javascript, Write a compareTo method for the Playlist class. Playlists with fewer songs on them come first. Playlists with the same number of songs come in alphabetical order by playlist name. Playlists with the same number of songs and same name can be considered equivalent (though this obviously isn’t exactly true).
// PlayList class
class PlayList {
constructor(nsongs, name) {
this.nsongs = nsongs;
this.name = name;
}
}
// compares number of songs if numbers are same then playlist names
function compareTo(a, b) {
if (a.nsongs > b.nsongs) return 1;
if (b.nsongs > a.nsongs) return -1;
return a.name.localeCompare(b.name);
}
// creating array and pushing elements
var list = [];
list.push( new PlayList(2,"Vammie"));
list.push( new PlayList(1,"Gimmie"));
list.push( new PlayList(2,"Samie"));
list.push( new PlayList(5,"Lamie"));
// Sort array based on compareTo function
list.sort(compareTo);
Output: