| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | const TupleSet = require("./TupleSet");
|
|---|
| 9 |
|
|---|
| 10 | /**
|
|---|
| 11 | * FIFO queue for tuples that preserves uniqueness by delegating membership
|
|---|
| 12 | * tracking to `TupleSet`.
|
|---|
| 13 | * @template T
|
|---|
| 14 | * @template V
|
|---|
| 15 | */
|
|---|
| 16 | class TupleQueue {
|
|---|
| 17 | /**
|
|---|
| 18 | * Seeds the queue with an optional iterable of tuples to visit.
|
|---|
| 19 | * @param {Iterable<[T, V, ...EXPECTED_ANY]>=} items The initial elements.
|
|---|
| 20 | */
|
|---|
| 21 | constructor(items) {
|
|---|
| 22 | /**
|
|---|
| 23 | * @private
|
|---|
| 24 | * @type {TupleSet<T, V>}
|
|---|
| 25 | */
|
|---|
| 26 | this._set = new TupleSet(items);
|
|---|
| 27 | /**
|
|---|
| 28 | * @private
|
|---|
| 29 | * @type {Iterator<[T, V, ...EXPECTED_ANY]>}
|
|---|
| 30 | */
|
|---|
| 31 | this._iterator = this._set[Symbol.iterator]();
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | /**
|
|---|
| 35 | * Returns the number of distinct tuples currently queued.
|
|---|
| 36 | * @returns {number} The number of elements in this queue.
|
|---|
| 37 | */
|
|---|
| 38 | get length() {
|
|---|
| 39 | return this._set.size;
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | /**
|
|---|
| 43 | * Enqueues a tuple if it is not already present in the underlying set.
|
|---|
| 44 | * @param {[T, V, ...EXPECTED_ANY]} item The element to add.
|
|---|
| 45 | * @returns {void}
|
|---|
| 46 | */
|
|---|
| 47 | enqueue(...item) {
|
|---|
| 48 | this._set.add(...item);
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | /**
|
|---|
| 52 | * Removes and returns the next queued tuple, rebuilding the iterator when
|
|---|
| 53 | * the underlying tuple set has changed since the last full pass.
|
|---|
| 54 | * @returns {[T, V, ...EXPECTED_ANY] | undefined} The head of the queue of `undefined` if this queue is empty.
|
|---|
| 55 | */
|
|---|
| 56 | dequeue() {
|
|---|
| 57 | const result = this._iterator.next();
|
|---|
| 58 | if (result.done) {
|
|---|
| 59 | if (this._set.size > 0) {
|
|---|
| 60 | this._iterator = this._set[Symbol.iterator]();
|
|---|
| 61 | const value =
|
|---|
| 62 | /** @type {[T, V, ...EXPECTED_ANY]} */
|
|---|
| 63 | (this._iterator.next().value);
|
|---|
| 64 | this._set.delete(...value);
|
|---|
| 65 | return value;
|
|---|
| 66 | }
|
|---|
| 67 | return;
|
|---|
| 68 | }
|
|---|
| 69 | this._set.delete(.../** @type {[T, V, ...EXPECTED_ANY]} */ (result.value));
|
|---|
| 70 | return result.value;
|
|---|
| 71 | }
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|
| 74 | module.exports = TupleQueue;
|
|---|