Last active
August 29, 2015 13:57
-
-
Save jonathanhculver/9714950 to your computer and use it in GitHub Desktop.
Javascript module pattern for Spotify Playlist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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