UNPKG

1.68 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2010-2014 original author or authors */
2/** @author Brian Cavalier */
3/** @author John Hann */
4
5(function(define) { 'use strict';
6define(function() {
7 /**
8 * Circular queue
9 * @param {number} capacityPow2 power of 2 to which this queue's capacity
10 * will be set initially. eg when capacityPow2 == 3, queue capacity
11 * will be 8.
12 * @constructor
13 */
14 function Queue(capacityPow2) {
15 this.head = this.tail = this.length = 0;
16 this.buffer = new Array(1 << capacityPow2);
17 }
18
19 Queue.prototype.push = function(x) {
20 if(this.length === this.buffer.length) {
21 this._ensureCapacity(this.length * 2);
22 }
23
24 this.buffer[this.tail] = x;
25 this.tail = (this.tail + 1) & (this.buffer.length - 1);
26 ++this.length;
27 return this.length;
28 };
29
30 Queue.prototype.shift = function() {
31 var x = this.buffer[this.head];
32 this.buffer[this.head] = void 0;
33 this.head = (this.head + 1) & (this.buffer.length - 1);
34 --this.length;
35 return x;
36 };
37
38 Queue.prototype._ensureCapacity = function(capacity) {
39 var head = this.head;
40 var buffer = this.buffer;
41 var newBuffer = new Array(capacity);
42 var i = 0;
43 var len;
44
45 if(head === 0) {
46 len = this.length;
47 for(; i<len; ++i) {
48 newBuffer[i] = buffer[i];
49 }
50 } else {
51 capacity = buffer.length;
52 len = this.tail;
53 for(; head<capacity; ++i, ++head) {
54 newBuffer[i] = buffer[head];
55 }
56
57 for(head=0; head<len; ++i, ++head) {
58 newBuffer[i] = buffer[head];
59 }
60 }
61
62 this.buffer = newBuffer;
63 this.head = 0;
64 this.tail = this.length;
65 };
66
67 return Queue;
68
69});
70}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));