forked from khrj/p-queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
priority-queue.ts
50 lines (41 loc) · 1.5 KB
/
priority-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
49
50
import lowerBound from "./lower-bound.ts"
import { QueueAddOptions } from "./options.ts"
import { Queue, RunFunction } from "./queue.ts"
export interface PriorityQueueOptions extends QueueAddOptions {
priority?: number
}
export default class PriorityQueue implements Queue<RunFunction, PriorityQueueOptions> {
private readonly _queue: Array<PriorityQueueOptions & { run: RunFunction }> = []
enqueue(run: RunFunction, options?: Partial<PriorityQueueOptions>): void {
options = {
priority: 0,
...options,
}
const element = {
priority: options.priority,
run,
}
if (this.size && this._queue[this.size - 1].priority! >= options.priority!) {
this._queue.push(element)
return
}
const index = lowerBound(
this._queue,
element,
(a: Readonly<PriorityQueueOptions>, b: Readonly<PriorityQueueOptions>) => b.priority! - a.priority!,
)
this._queue.splice(index, 0, element)
}
dequeue(): RunFunction | undefined {
const item = this._queue.shift()
return item?.run
}
filter(options: Readonly<Partial<PriorityQueueOptions>>): RunFunction[] {
return this._queue.filter(
(element: Readonly<PriorityQueueOptions>) => element.priority === options.priority,
).map((element: Readonly<{ run: RunFunction }>) => element.run)
}
get size(): number {
return this._queue.length
}
}