1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | export default function Queue (capPow2) {
|
8 | this._capacity = capPow2 || 32
|
9 | this._length = 0
|
10 | this._head = 0
|
11 | }
|
12 |
|
13 | Queue.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 |
|
22 | Queue.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 |
|
32 | Queue.prototype.isEmpty = function () {
|
33 | return this._length === 0
|
34 | }
|
35 |
|
36 | Queue.prototype.length = function () {
|
37 | return this._length
|
38 | }
|
39 |
|
40 | Queue.prototype._checkCapacity = function (size) {
|
41 | if (this._capacity < size) {
|
42 | this._ensureCapacity(this._capacity << 1)
|
43 | }
|
44 | }
|
45 |
|
46 | Queue.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 |
|
57 | function 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 | }
|