Skip to content

Instantly share code, notes, and snippets.

@padolsey
Created December 11, 2009 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save padolsey/253916 to your computer and use it in GitHub Desktop.
Save padolsey/253916 to your computer and use it in GitHub Desktop.
// SELECTING JQUERY COOKBOOK WINNERS
var RandomNumberGen = (function(){
// Random num generator
// Never returns the same number twice
function RandomNumberGen(min, max) {
this.used = {};
this.min = min || 0;
this.max = max || 9999999;
}
RandomNumberGen.prototype.gen = function() {
var i, attempts = 0,
max = this.max,
min = this.min,
used = this.used;
while ( used[i = Math.floor(Math.random() * (max - min + 1) + min)] ) {
if ( attempts++ > max-min ) {
return null;
}
}
used[i] = true;
return i;
};
RandomNumberGen.prototype.avoid = function(n) {
return this.used[n] = true;
};
return RandomNumberGen;
})();
var randomCommentGen = new RandomNumberGen(0, 255),
numberOfBooks = 5,
comments = jQuery('.commentlist li');
randomCommentGen.avoid(7); // A comment from me
randomCommentGen.avoid(255); // Another comment from me
for (var i = 0; i < numberOfBooks; ++i) {
var rand = randomCommentGen.gen();
if ( rand !== null ) {
comments.eq( rand ).css({
// Highlight winner
backgroundColor: 'yellow',
color: 'red',
fontWeight: 700
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment