-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathqueue.ts
48 lines (38 loc) · 1.01 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
import { pushTo } from './common.js';
export class Queue<T> {
private _evictListeners: ((item: T) => void)[] = [];
public onEvict = pushTo(this._evictListeners);
constructor(private _items: T[] = [], private _limit: number = null) {}
enqueue(item: T) {
const items = this._items;
items.push(item);
if (this._limit && items.length > this._limit) this.evict();
return item;
}
evict(): T {
const item: T = this._items.shift();
this._evictListeners.forEach((fn) => fn(item));
return item;
}
dequeue(): T {
if (this.size()) return this._items.splice(0, 1)[0];
}
clear(): Array<T> {
const current = this._items;
this._items = [];
return current;
}
size(): number {
return this._items.length;
}
remove(item: T) {
const idx = this._items.indexOf(item);
return idx > -1 && this._items.splice(idx, 1)[0];
}
peekTail(): T {
return this._items[this._items.length - 1];
}
peekHead(): T {
if (this.size()) return this._items[0];
}
}