Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Last active December 10, 2018 18:18
Show Gist options
  • Save friendlyanon/afd5a18811c540bc8bcf3f40560d4c74 to your computer and use it in GitHub Desktop.
Save friendlyanon/afd5a18811c540bc8bcf3f40560d4c74 to your computer and use it in GitHub Desktop.
"use strict";
const { toString } = Object.prototype;
class Queue {
constructor(list) {
this._clearThreshold = 50;
this._offset = 0;
this._list = [];
this.enqueueIterable(list);
}
enqueue(item) { return this._list.push(item), this; }
enqueueMore(...items) { return items.push.apply(this._list, items), this; }
enqueueIterable(iterable) {
if (iterable == null || typeof iterable !== "object") return this;
if (toString.call(iterable) === "[object Array]") {
this._list = this._list.concat(iterable);
}
else other: {
const it = iterable[Symbol.iterator];
if (typeof it === "function") {
this._list = this._list.concat([...it.call(iterable)]);
break other;
}
const l = iterable.length;
if (typeof l !== "number") break other;
const { _list } = this;
for (let i = 0, k = _list.length - 1; i < l; ++i) _list[++k] = iterable[i];
}
return this;
}
dequeue() {
const { _list } = this;
if (!_list.length) return;
const result = _list[this._offset];
if (++this._offset >= _list.length) {
this._list = [];
this._offset = 0;
}
else {
if (this._offset >= this._clearThreshold) {
this._list = _list.slice(this._clearThreshold - 1);
this._offset = 0;
}
// clear dequeued elements with 0 to retain the array's elements kind
// attribute in best case scenarios:
// PACKED_SMI_ELEMENTS or PACKED_DOUBLE_ELEMENTS
else _list[this._offset - 1] = 0;
}
return result;
}
peek() { return !this._list.length ? void 0 : this._list[this._offset]; }
isEmpty() { return this.size() <= 0; }
size() { return this._list.length - this._offset; }
*values () { while (this._list.length) yield this.dequeue(); }
giveAll() {
if (!this._list.length) return [];
const { _list, _offset } = this;
this._list = [];
this._offset = 0;
return _list.slice(_offset);
}
} // class Queue
Object.defineProperty(Queue.prototype, Symbol.iterator, {
value: Queue.prototype.values,
writable: true,
configurable: true
});
module.exports = Queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment