source: trip-planner-front/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.6 KB
Line 
1'use strict';
2
3var RingBuffer = function(bufferSize) {
4 this._bufferSize = bufferSize;
5 this.clear();
6};
7
8RingBuffer.prototype.clear = function() {
9 this._buffer = new Array(this._bufferSize);
10 this._ringOffset = 0;
11 this._ringSize = this._bufferSize;
12 this._head = 0;
13 this._tail = 0;
14 this.length = 0;
15};
16
17RingBuffer.prototype.push = function(value) {
18 var expandBuffer = false,
19 expandRing = false;
20
21 if (this._ringSize < this._bufferSize) {
22 expandBuffer = (this._tail === 0);
23 } else if (this._ringOffset === this._ringSize) {
24 expandBuffer = true;
25 expandRing = (this._tail === 0);
26 }
27
28 if (expandBuffer) {
29 this._tail = this._bufferSize;
30 this._buffer = this._buffer.concat(new Array(this._bufferSize));
31 this._bufferSize = this._buffer.length;
32
33 if (expandRing)
34 this._ringSize = this._bufferSize;
35 }
36
37 this._buffer[this._tail] = value;
38 this.length += 1;
39 if (this._tail < this._ringSize) this._ringOffset += 1;
40 this._tail = (this._tail + 1) % this._bufferSize;
41};
42
43RingBuffer.prototype.peek = function() {
44 if (this.length === 0) return void 0;
45 return this._buffer[this._head];
46};
47
48RingBuffer.prototype.shift = function() {
49 if (this.length === 0) return void 0;
50
51 var value = this._buffer[this._head];
52 this._buffer[this._head] = void 0;
53 this.length -= 1;
54 this._ringOffset -= 1;
55
56 if (this._ringOffset === 0 && this.length > 0) {
57 this._head = this._ringSize;
58 this._ringOffset = this.length;
59 this._ringSize = this._bufferSize;
60 } else {
61 this._head = (this._head + 1) % this._ringSize;
62 }
63 return value;
64};
65
66module.exports = RingBuffer;
Note: See TracBrowser for help on using the repository browser.