Skip to content

Instantly share code, notes, and snippets.

@jonathanhculver
Last active August 29, 2015 13:57
Show Gist options
  • Save jonathanhculver/9714950 to your computer and use it in GitHub Desktop.
Save jonathanhculver/9714950 to your computer and use it in GitHub Desktop.
Javascript module pattern for Spotify Playlist
var playlistModule = (function() {
/* private var */
var tracksArray = [],
shuffleArray = [];
/* public methods */
var addTrack = function(uri) {
tracksArray.push(uri);
return tracksArray;
}
var removeTrack = function(uri) {
var index = findTrackIndex(uri);
tracksArray.splice(index, 1);
return tracksArray;
}
var getTracks = function() {
return tracksArray;
}
var shuffleTracks = function() {
var tempArray = [];
var maxNum = tracksArray.length;
/* made a copy of the array */
shuffleArray = tracksArray.slice(0);
for(var i=0, max = tracksArray.length; i<max; i++) {
var randomNum = Math.floor(Math.random() * maxNum);
var nextTrack = shuffleArray[randomNum];
markPlayed(randomNum);
tempArray.push(nextTrack);
maxNum--;
}
return tempArray;
}
/* private utility methods */
var markPlayed = function(index) {
shuffleArray.splice(index, 1);
}
var findTrackIndex = function(uri) {
for(var i = 0; i< tracksArray.length; i++) {
if(tracksArray[i] == uri) {
return i;
}
}
}
//only return methods we want public
return {
getTracks: getTracks,
removeTrack: removeTrack,
addTrack: addTrack,
shuffleTracks: shuffleTracks
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment