1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.PrioritizedTaskExecutor = void 0;
|
4 | class PrioritizedTaskExecutor {
|
5 | /**
|
6 | * Executes tasks up to maxPoolSize at a time, other items are put in a priority queue.
|
7 | * @class PrioritizedTaskExecutor
|
8 | * @private
|
9 | * @param maxPoolSize The maximum size of the pool
|
10 | */
|
11 | constructor(maxPoolSize) {
|
12 | this.maxPoolSize = maxPoolSize;
|
13 | this.currentPoolSize = 0;
|
14 | this.queue = [];
|
15 | }
|
16 | /**
|
17 | * Executes the task or queues it if no spots are available.
|
18 | * When a task is added, check if there are spots left in the pool.
|
19 | * If a spot is available, claim that spot and give back the spot once the asynchronous task has been resolved.
|
20 | * When no spots are available, add the task to the task queue. The task will be executed at some point when another task has been resolved.
|
21 | * @private
|
22 | * @param priority The priority of the task
|
23 | * @param fn The function that accepts the callback, which must be called upon the task completion.
|
24 | */
|
25 | executeOrQueue(priority, fn) {
|
26 | if (this.currentPoolSize < this.maxPoolSize) {
|
27 | this.currentPoolSize++;
|
28 | fn(() => {
|
29 | this.currentPoolSize--;
|
30 | if (this.queue.length > 0) {
|
31 | this.queue.sort((a, b) => b.priority - a.priority);
|
32 | const item = this.queue.shift();
|
33 | this.executeOrQueue(item.priority, item.fn);
|
34 | }
|
35 | });
|
36 | }
|
37 | else {
|
38 | this.queue.push({ priority, fn });
|
39 | }
|
40 | }
|
41 | /**
|
42 | * Checks if the taskExecutor is finished.
|
43 | * @private
|
44 | * @returns Returns `true` if the taskExecutor is finished, otherwise returns `false`.
|
45 | */
|
46 | finished() {
|
47 | return this.currentPoolSize === 0;
|
48 | }
|
49 | }
|
50 | exports.PrioritizedTaskExecutor = PrioritizedTaskExecutor;
|
51 | //# sourceMappingURL=prioritizedTaskExecutor.js.map |
\ | No newline at end of file |