2018-07-30 23:08:51 +08:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Tobias Koppers @sokra
|
|
|
|
*/
|
|
|
|
|
2017-10-13 01:12:48 +08:00
|
|
|
"use strict";
|
|
|
|
|
2018-04-15 04:19:36 +08:00
|
|
|
/**
|
|
|
|
* @template T
|
|
|
|
*/
|
2024-12-04 17:23:52 +08:00
|
|
|
class Queue {
|
2018-04-15 04:19:36 +08:00
|
|
|
/**
|
2024-12-04 17:23:52 +08:00
|
|
|
* @param {Iterable<T>=} items The initial elements.
|
2018-04-15 04:19:36 +08:00
|
|
|
*/
|
2024-12-04 17:23:52 +08:00
|
|
|
constructor(items) {
|
|
|
|
/**
|
|
|
|
* @private
|
|
|
|
* @type {Set<T>}
|
|
|
|
*/
|
|
|
|
this._set = new Set(items);
|
2018-01-11 20:25:26 +08:00
|
|
|
}
|
|
|
|
|
2024-12-04 17:23:52 +08:00
|
|
|
/**
|
|
|
|
* Returns the number of elements in this queue.
|
|
|
|
* @returns {number} The number of elements in this queue.
|
|
|
|
*/
|
|
|
|
get length() {
|
|
|
|
return this._set.size;
|
2017-10-13 01:12:48 +08:00
|
|
|
}
|
|
|
|
|
2018-04-15 04:19:36 +08:00
|
|
|
/**
|
|
|
|
* Appends the specified element to this queue.
|
|
|
|
* @param {T} item The element to add.
|
2018-05-08 20:31:51 +08:00
|
|
|
* @returns {void}
|
2018-04-15 04:19:36 +08:00
|
|
|
*/
|
2017-10-13 01:12:48 +08:00
|
|
|
enqueue(item) {
|
2024-12-04 17:23:52 +08:00
|
|
|
this._set.add(item);
|
2017-10-13 01:12:48 +08:00
|
|
|
}
|
|
|
|
|
2018-04-15 04:19:36 +08:00
|
|
|
/**
|
|
|
|
* Retrieves and removes the head of this queue.
|
2018-05-08 20:31:51 +08:00
|
|
|
* @returns {T | undefined} The head of the queue of `undefined` if this queue is empty.
|
2018-04-15 04:19:36 +08:00
|
|
|
*/
|
2017-10-13 01:12:48 +08:00
|
|
|
dequeue() {
|
2024-12-04 17:23:52 +08:00
|
|
|
const result = this._set[Symbol.iterator]().next();
|
|
|
|
if (result.done) return;
|
|
|
|
this._set.delete(result.value);
|
|
|
|
return result.value;
|
2017-10-13 01:12:48 +08:00
|
|
|
}
|
2018-04-15 04:19:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Queue;
|