Create a gist now

Instantly share code, notes, and snippets.

Embed
Random generator class & object
/*
Script made by Zzortell: http://php-zzortell.rhcloud.com/
Basic usage:
Zz.random.draw(); // return 0 or 1
Zz.random.draw(99); // return int between 0 and 99
Zz.random.drawBetween(1, 6); // return int between 1 and 6
Zz.random.drawIn(['female', 'male']); // return an item of the array
Complex usage:
random = new Zz.Random (['lady', 'gentleman']);
random.drawIn(); // return 'lady' or 'gentleman'
random.drawIn(['girl', 'boy']); // return 'girl' or 'boy'
random.drawIn(); // return 'girl' or 'boy'
*/
var Zz = Zz || {};
Zz.Random = function ( multi, inf, sup ) {
this.max = 1;
this.inf = null;
this.sup = null;
this.items = null;
if ( typeof multi === 'number' && max > 0 ) {
this.max = multi;
} else if ( multi instanceof Array && items.length > 1 ) {
this.items = multi;
}
if (
typeof inf === 'number' && inf >= 0
&& typeof sup === 'number' && sup > 0
&& inf < sup
) {
this.inf = inf;
this.sup = sup;
}
};
Zz.random = new Zz.Random ();
Zz.Random.prototype.draw = function ( max ) {
if ( typeof max === 'number' && max > 0 ) {
this.max = max;
}
return parseInt(Math.random()*(this.max+1));
};
Zz.Random.prototype.drawBetween = function ( inf, sup ) {
if (
typeof inf === 'number' && inf >= 0
&& typeof sup === 'number' && sup > 0
&& inf < sup
) {
this.inf = inf;
this.sup = sup;
}
if ( this.inf === null || this.sup === null ) {
return false;
}
var diff = this.sup - this.inf;
return this.draw(diff) + inf;
};
Zz.Random.prototype.drawIn = function ( items ) {
if ( items instanceof Array && items.length > 1 ) {
this.items = items;
}
if ( !(this.items instanceof Array) ) {
return false;
}
return this.items[this.draw(this.items.length-1)];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment