UNPKG

1.37 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2010-2016 original author or authors */
2/** @author Brian Cavalier */
3/** @author John Hann */
4
5// Based on https://github.com/petkaantonov/deque
6
7export default function Queue (capPow2) {
8 this._capacity = capPow2 || 32
9 this._length = 0
10 this._head = 0
11}
12
13Queue.prototype.push = function (x) {
14 var len = this._length
15 this._checkCapacity(len + 1)
16
17 var i = (this._head + len) & (this._capacity - 1)
18 this[i] = x
19 this._length = len + 1
20}
21
22Queue.prototype.shift = function () {
23 var head = this._head
24 var x = this[head]
25
26 this[head] = void 0
27 this._head = (head + 1) & (this._capacity - 1)
28 this._length--
29 return x
30}
31
32Queue.prototype.isEmpty = function () {
33 return this._length === 0
34}
35
36Queue.prototype.length = function () {
37 return this._length
38}
39
40Queue.prototype._checkCapacity = function (size) {
41 if (this._capacity < size) {
42 this._ensureCapacity(this._capacity << 1)
43 }
44}
45
46Queue.prototype._ensureCapacity = function (capacity) {
47 var oldCapacity = this._capacity
48 this._capacity = capacity
49
50 var last = this._head + this._length
51
52 if (last > oldCapacity) {
53 copy(this, 0, this, oldCapacity, last & (oldCapacity - 1))
54 }
55}
56
57function copy (src, srcIndex, dst, dstIndex, len) {
58 for (var j = 0; j < len; ++j) {
59 dst[j + dstIndex] = src[j + srcIndex]
60 src[j + srcIndex] = void 0
61 }
62}