fix: perf regression

This commit is contained in:
Alexander Akait 2024-12-05 17:01:21 +03:00 committed by GitHub
commit eb7ac6f39a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 22 additions and 55 deletions

View File

@ -5,28 +5,27 @@
"use strict";
/**
* @template T
*/
class Node {
/**
* @param {T} value the value
*/
constructor(value) {
this.value = value;
/** @type {Node<T> | undefined} */
this.next = undefined;
}
}
/**
* @template T
*/
class Queue {
constructor() {
this._head = undefined;
this._tail = undefined;
this._size = 0;
/**
* @param {Iterable<T>=} items The initial elements.
*/
constructor(items) {
/**
* @private
* @type {Set<T>}
*/
this._set = new Set(items);
}
/**
* Returns the number of elements in this queue.
* @returns {number} The number of elements in this queue.
*/
get length() {
return this._set.size;
}
/**
@ -35,18 +34,7 @@ class Queue {
* @returns {void}
*/
enqueue(item) {
const node = new Node(item);
if (this._head) {
/** @type {Node<T>} */
(this._tail).next = node;
this._tail = node;
} else {
this._head = node;
this._tail = node;
}
this._size++;
this._set.add(item);
}
/**
@ -54,31 +42,10 @@ class Queue {
* @returns {T | undefined} The head of the queue of `undefined` if this queue is empty.
*/
dequeue() {
const current = this._head;
if (!current) {
return;
}
this._head = this._head.next;
this._size--;
return current.value;
}
/**
* Returns the number of elements in this queue.
* @returns {number} The number of elements in this queue.
*/
get length() {
return this._size;
}
*[Symbol.iterator]() {
let current = this._head;
while (current) {
yield current.value;
current = current.next;
}
const result = this._set[Symbol.iterator]().next();
if (result.done) return;
this._set.delete(result.value);
return result.value;
}
}