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
// 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