blowery (owner)

Revisions

gist: 204087 Download_button fork
public
Public Clone URL: git://gist.github.com/204087.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
64
65
// A RingBufffer
 
function RingBuffer(sz) {
    this._max = sz;
    this._buffer = new Array(sz);
    this._head = -1;
}
 
RingBuffer.prototype = {
 
    push: function(el){
        // summary: Push a new element into the ring buffer.
        // May discard the oldest existing element.
        var h = this._head + 1;
        if(h === this._max) h = 0; // wrap to the beginning
        this._buffer[h] = el;
        this._head = h;
        return this;
    },
 
    pop: function(){
        // summary: Pull the most recently pushed element out of
        // the buffer.
        var el = this._buffer[this._head];
        if(el === undefined) {
            return undefined;
        }
 
        var h = this._head - 1;
        if(h === -1 && this._buffer[this._max-1] !== undefined) {
            h = this._max-1;
        }
        this._buffer[this._head] = undefined;
        this._head = h;
        return el;
    },
 
    _visit: function(fn){
        var l=0,h=this._head;
        while(this._buffer[h] !== undefined && l !== this._max) {
            if(fn) fn(this._buffer[h], l);
            l++; h--;
            if(h === -1 && this._buffer[this._max - 1] !== undefined) {
                h = this._max - 1;
            }
        }
        return l;
    },
 
    length: function(){
        return this._visit();
    },
 
    toArray: function(){
        var ar = [];
        this._visit(function(el) { ar.push(el); } );
        return ar;
    },
 
    toString: function(){
        var body = this.length() === 0 ? "" : "[ " + this.toArray().join(", ") + " ]";
        return "[RingBuffer " + body + "]";
    }
};