Created
December 1, 2015 11:55
-
-
Save HakurouKen/13afaca3d85c2fb92cc4 to your computer and use it in GitHub Desktop.
A simple javascript random library.
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
(function (root, factory) { | |
if (typeof define === 'function' && define.amd) { | |
define([], factory); | |
} else if (typeof exports === 'object') { | |
module.exports = factory(); | |
} else { | |
root['strHash'] = factory(); | |
} | |
}(this, function () { | |
var Random = {}; | |
var _rand = Math.random, | |
max = Math.max, | |
min = Math.min, | |
floor = Math.floor, | |
ceil = Math.ceil | |
round = Math.round; | |
function type(o){ | |
return Object.prototype.toString.call(o).slice(8,-1).toLowerCase(); | |
} | |
function isNumber(o){ | |
return type(o) === 'number'; | |
} | |
var isInt = Number && Number.isInteger ? Number.isInteger : function(n){ | |
return n >> 0 === n; | |
}; | |
function checkInt(name,val){ | |
if( !isInt(val) ){ | |
throw new Error('params ' + (name || '') + 'must be integer.'); | |
} | |
return; | |
} | |
function checkNum(name,val){ | |
if( !isNumber(val) ){ | |
throw new Error('params ' + (name || '') + 'is not a number.'); | |
} | |
return; | |
} | |
Random.random = function(start,stop){ | |
var argNum = arguments.length; | |
if( argNum === 1 ){ | |
stop = start; | |
start = 0; | |
} else if( argNum === 0 ){ | |
start = 0; | |
stop = 1; | |
} | |
checkNum('start',start); | |
checkNum('stop',stop); | |
return start + (stop - start)*_rand(); | |
} | |
Random.randomInt = function(start,stop,step){ | |
if( !stop ){ | |
stop = start; | |
start = 0; | |
} | |
step = step || 1; | |
checkInt('start',start); | |
checkInt('stop',stop); | |
checkInt('step',step); | |
var n = (stop - start) / step >> 0; | |
return start + step * (n * _rand() >> 0); | |
} | |
Random.choice = function(seq){ | |
return seq[this.randomInt(seq.length)]; | |
}; | |
Random.shuffle = function(seq){ | |
var rand, | |
shuffled = []; | |
for( var i = 0, l = seq.length; i < l; i++ ){ | |
rand = Random.random(i) | |
shuffled[i] = shuffled[rand]; | |
shuffled[rand] = seq[i]; | |
} | |
return shuffled; | |
}; | |
Random.sample = function(population,k){ | |
return Random.shuffled(population).slice(k); | |
}; | |
return Random; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment