Skip to content

Instantly share code, notes, and snippets.

@padolsey padolsey/gist:253916
Created Dec 11, 2009

Embed
What would you like to do?
// 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
You can’t perform that action at this time.