Skip to content

Instantly share code, notes, and snippets.

@JSRossiter
Created May 3, 2017 23:07
Show Gist options
  • Save JSRossiter/2d7edc8e25657a50aa70fca8475930c4 to your computer and use it in GitHub Desktop.
Save JSRossiter/2d7edc8e25657a50aa70fca8475930c4 to your computer and use it in GitHub Desktop.
Music library using object prototypes
var uid = function() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
function Library (name, creator) {
this.name = name;
this.creator = creator;
this.playlists = [];
this.tracks = [];
}
function Playlist (name) {
this.name = name;
this.id = uid();
this.tracks = [];
}
function Track (name, rating, length) {
this.name = name;
this.rating = rating;
this.length = length;
this.id = uid();
}
Library.prototype.createPlaylist = function (name) {
this.playlists.push(new Playlist(name));
}
Playlist.prototype.addTrack = function (title, rating, length) {
this.tracks.push(new Track(title, rating, length));
}
Object.defineProperty(Playlist.prototype, 'overallRating', {
get: function() {
const sum = this.tracks.reduce((acc, track) => {
return acc + track.rating;
}, 0);
return Math.round((sum / this.tracks.length) * 10) / 10;
}
})
Object.defineProperty(Playlist.prototype, 'totalLength', {
get: function() {
return this.tracks.reduce((acc, track) => {
return acc + track.length;
}, 0);
}
})
const lib = new Library ('Jeffs Library', 'Jeff');
lib.createPlaylist('a playlist');
lib.playlists[0].addTrack('a track', 5, 100);
lib.playlists[0].addTrack('b track', 4, 900);
lib.playlists[0].addTrack('c track', 4, 900);
lib.playlists[0].addTrack('d track', 4, 900);
lib.playlists[0].addTrack('d track', 3, 550);
lib.playlists[0].addTrack('e track', 2, 550);
lib.playlists[0].addTrack('f track', 2, 275);
console.log('Library:', lib);
console.log('Overall rating:', lib.playlists[0].overallRating);
console.log('Total length:', lib.playlists[0].totalLength);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment