UNPKG

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