UNPKG

1.05 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8/**
9 * @template T
10 */
11class Queue {
12 /**
13 * @param {Iterable<T>=} items The initial elements.
14 */
15 constructor(items) {
16 /** @private @type {Set<T>} */
17 this._set = new Set(items);
18 /** @private @type {Iterator<T>} */
19 this._iterator = this._set[Symbol.iterator]();
20 }
21
22 /**
23 * Returns the number of elements in this queue.
24 * @returns {number} The number of elements in this queue.
25 */
26 get length() {
27 return this._set.size;
28 }
29
30 /**
31 * Appends the specified element to this queue.
32 * @param {T} item The element to add.
33 * @returns {void}
34 */
35 enqueue(item) {
36 this._set.add(item);
37 }
38
39 /**
40 * Retrieves and removes the head of this queue.
41 * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty.
42 */
43 dequeue() {
44 const result = this._iterator.next();
45 if (result.done) return undefined;
46 this._set.delete(result.value);
47 return result.value;
48 }
49}
50
51module.exports = Queue;