DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Randomizer //Javascript Class

09.08.2005
| 769 views |
  • submit to reddit
        <a href="http://jsfromhell.com/classes/randomizer">
Simple randomizer, also with probability randomizing.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

Code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/randomizer [v1.0]

Randomizer = function( type ){
	var o = this;
	( o.d = [], o.t = type || Randomizer.RANDOMIZED, o.x = -1, o.u = 0 );
};
with( { o: Randomizer, p: Randomizer.prototype } ){
	o.SEQUENCED = ( o.PROBABILITY = ( o.RANDOMIZED = 0 ) + 1 ) + 1;
	p.add = function( object, probability ){
		this.u += ( this.d[ this.d.length ] = { o: object, p: Math.abs( probability || 1 ) } ).p;
	};
	p.remove = function( index ){
		if( index > -1 && index < this.d.length )
			this.u -= this.d.splice( index, 1 ).p;
	};
	p.next = function(){
		if( !this.u ) return null;
		var i = 0, m = 0, x = this.t == Randomizer.SEQUENCED ? ( this.x = ( this.x + 1 ) % this.d.length ) : Math.round( Math.random() * ( this.t == Randomizer.PROBABILITY ? this.u : this.d.length - 1 ) );
		if( this.t == Randomizer.PROBABILITY ){
			do m += this.d[ i++ ].p;
			while( x > m || !( ( x = --i ) + 1 ) );
		}
		return this.d[ x ].o;
	};
}


Example

//can be also RANDOMIZED and SEQUENCED...

x = new Randomizer( Randomizer.PROBABILITY );

x.add( "I have more chances than everybody :]", 20 );
x.add( "I have good chances", 10 );
x.add( "I'm difficult to appear...", 1 );

for( i = 10; i--; document.write( x.next(), '\n' ) );