-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathqueue.ts
More file actions
35 lines (32 loc) 路 899 Bytes
/
Copy pathqueue.ts
File metadata and controls
35 lines (32 loc) 路 899 Bytes
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
/**
* First In First Out (FIFO)
* with time complexity of O(1) for key operations
*/
export class Queue<T>{
private data: { [index: number]: T } = Object.create(null);
private nextEnqueueIndex = 0;
private lastDequeuedIndex = 0;
/** Enqueues the item in O(1) */
enqueue(item: T): void {
this.data[this.nextEnqueueIndex] = item;
this.nextEnqueueIndex++;
}
/**
* Dequeues the first inserted item in O(1)
* If there are no more items it returns `undefined`
*/
dequeue(): T | undefined {
if (this.lastDequeuedIndex !== this.nextEnqueueIndex) {
const dequeued = this.data[this.lastDequeuedIndex];
delete this.data[this.lastDequeuedIndex];
this.lastDequeuedIndex++;
return dequeued;
}
}
/**
* Returns the number of elements in the queue
*/
size(): number {
return this.nextEnqueueIndex - this.lastDequeuedIndex;
}
}