Skip to content

Instantly share code, notes, and snippets.

@watert
Created August 29, 2013 02:10
Show Gist options
  • Select an option

  • Save watert/6373565 to your computer and use it in GitHub Desktop.

Select an option

Save watert/6373565 to your computer and use it in GitHub Desktop.
advanced random methods for underscore
/*
_.random.str() : "Quick"
_.random.str(3) : "Jumps Jumps Fox"
_.random.list() : [43, 65, 52, 65, 49]
_.random.list(3) : [43, 65, 49]
*/
(function(){
var methods = {
num:function(num1,num2){
num1=num1||100;
return _.random(num1,num2);
},
str:function(wordCount,words){
if(!words && typeof wordCount == "string"){
words = wordCount;
wordCount=1;
}
wordCount = wordCount||1;
words = words||"The Quick Brown Fox Jumps Over The Lazy Dog".split(" ");
str = _.random.select(words,wordCount).join(" ");
return str;
},
select:function(vals,count){
count = count||1;
vals = vals||_.range(10);
return _.random.list(count,function(){
return vals[_.random.num(vals.length-1)]
});
},
list:function(count,callback){
count = count||5;
var range = _.range(count);
if(!callback)callback = function(){
return _.random.num();
};
return _.map(range,callback);
}
};
function setup(){
_.extend(_.random,methods);
return _.random;
}
if(window._)setup();
if(window.define&&window.require){
define("_.random",["underscore"],setup);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment