-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.ts
35 lines (30 loc) · 828 Bytes
/
queue.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
// 2021-08-27 - Based on simple example here: https://www.telerik.com/blogs/stack-queue-javascript
//
/**
* A simple queue implementation.
*
* @category Low-Level
*/
export class Queue<T> {
private _queue: { [index: number]: T } = {};
private _tail = 0;
private _head = 0;
public get length(): number {
return this._tail - this._head;
}
// Add an element to the end of the queue.
public enqueue(element: T): void {
if (element === undefined) {
throw new TypeError('cannot enqueue `undefined`');
}
this._queue[this._tail++] = element;
}
// Delete the first element of the queue.
public dequeue(): T | undefined {
if (this._tail === this._head) return undefined;
const element = this._queue[this._head];
delete this._queue[this._head++];
return element;
}
}