Advertisement
Guest User

Untitled

a guest
Apr 16th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function pickSong(obj, kw) {
  2.     //if no kw is given
  3.     if (!kw) {
  4.         console.log("returning random song, no kw");
  5.         //select a random index within the song list
  6.         return Math.floor(Math.random() * (Object.keys(obj).length - 1)) + 1;
  7.     //if a kw is given
  8.     } else {
  9.         console.log("searching for song " + kw);
  10.  
  11.         //data parsed with an & in it will cause problems, so we replace it
  12.         var queue = kw.replace(/&/g, '&');
  13.  
  14.         //use the quote function to sanitize the kw input before creating the regexp pattern
  15.         var newqueue = new RegExp(RegExp.quote(queue), "i");
  16.  
  17.         // array for all matching songs
  18.         var found = [];
  19.  
  20.         // index for found array
  21.         var j = 0;
  22.  
  23.         //number of keys
  24.         var size = Object.keys(obj).length;
  25.         Object.keys(obj).forEach(function(key) {
  26.             if (key.match(newqueue)) {
  27.  
  28.                 found[j] = obj[key];
  29.                 j++;
  30.             }
  31.  
  32.  
  33.         });
  34.  
  35.             // if we get to the end of the array with no matches, return a random song
  36.         if (found.length == 0) {
  37.            
  38.             console.log("search failed for " + kw + ", returning random");
  39.  
  40.             //select a random index within the song list
  41.             return Math.floor(Math.random() * (Object.keys(obj).length - 1)) + 1;
  42.         }
  43.         //if we have multiple matches, select one at random
  44.         else if(found.length > 1) {
  45.  
  46.             //aIndex is used to match the key from found[] back to the original keys[] array
  47.             var aIndex = Math.floor(Math.random() * (found.length - 1)) + 1;
  48.  
  49.         //if only 1 song is matched, set the index to 0 to match that one song            
  50.         } else { var aIndex = 0;}
  51.  
  52.         return found[aIndex];
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement