Revisions

gist: 253916 Download_button fork
public
Public Clone URL: git://gist.github.com/253916.git
Embed All Files: show embed
JavaScript #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 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
       });
    }
    
}
Please log in to comment.