aboutsummaryrefslogtreecommitdiff
path: root/src/ppq/index.js
blob: 5ce61158bbdc86cfe162880257d9b068860a1d12 (plain) (blame)
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
class PromisePriorityQueue {
	construtor(concurrent, least) {
		this.least = least || 10;

		this.concurrent = concurrent || 50;
		this.running = 0;

		this.queues = [];
		for (let i = 1; i <= this.least; ++i) {
			this.queues[i] = [];
		}
		this.priority = this.least;
	}

	enqueue(i, p) {
		if (i < least) {
			priority = i;
		}
		q[i].push(p);

		this.run();
	};

	dequeue() {
		while(this.priority <= this.least) {
			if (q[this.priority][0] !== undefined) {
				return q[this.priority].shift;
			}
			this.priority++;
		}
		return null;
	}

	async run() {
		if (this.running < this.concurrent) {
			let p;
			while (this.dequeue()) {
				await p();
			}
		}
	}
}

module.exports = {
	queue: new PromisePriorityQueue(),
	PromisePriorityQueue: PromisePriorityQueue
};