Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pickSong(obj, kw) {
- //if no kw is given
- if (!kw) {
- console.log("returning random song, no kw");
- //select a random index within the song list
- return Math.floor(Math.random() * (Object.keys(obj).length - 1)) + 1;
- //if a kw is given
- } else {
- console.log("searching for song " + kw);
- //data parsed with an & in it will cause problems, so we replace it
- var queue = kw.replace(/&/g, '&');
- //use the quote function to sanitize the kw input before creating the regexp pattern
- var newqueue = new RegExp(RegExp.quote(queue), "i");
- // array for all matching songs
- var found = [];
- // index for found array
- var j = 0;
- //number of keys
- var size = Object.keys(obj).length;
- Object.keys(obj).forEach(function(key) {
- if (key.match(newqueue)) {
- found[j] = obj[key];
- j++;
- }
- });
- // if we get to the end of the array with no matches, return a random song
- if (found.length == 0) {
- console.log("search failed for " + kw + ", returning random");
- //select a random index within the song list
- return Math.floor(Math.random() * (Object.keys(obj).length - 1)) + 1;
- }
- //if we have multiple matches, select one at random
- else if(found.length > 1) {
- //aIndex is used to match the key from found[] back to the original keys[] array
- var aIndex = Math.floor(Math.random() * (found.length - 1)) + 1;
- //if only 1 song is matched, set the index to 0 to match that one song
- } else { var aIndex = 0;}
- return found[aIndex];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement