forked from ethereumjs/merkle-patricia-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprioritizedTaskExecutor.js
43 lines (40 loc) · 1.23 KB
/
prioritizedTaskExecutor.js
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
module.exports = PrioritizedTaskExecutor
/**
* Executes tasks up to maxPoolSize at a time, other items are put in a priority queue.
* @class PrioritizedTaskExecutor
* @param {Number} maxPoolSize The maximum size of the pool
* @prop {Number} maxPoolSize The maximum size of the pool
* @prop {Number} currentPoolSize The current size of the pool
* @prop {Array} queue The task queue
*/
function PrioritizedTaskExecutor (maxPoolSize) {
this.maxPoolSize = maxPoolSize
this.currentPoolSize = 0
this.queue = []
}
/**
* Executes the task.
* @param {Number} priority The priority of the task
* @param {Function} task The function that accepts the callback, which must be called upon the task completion.
*/
PrioritizedTaskExecutor.prototype.execute = function (priority, task) {
var self = this
if (self.currentPoolSize < self.maxPoolSize) {
self.currentPoolSize++
task(function () {
self.currentPoolSize--
if (self.queue.length > 0) {
self.queue.sort(function (a, b) {
return b.priority - a.priority
})
var item = self.queue.shift()
self.execute(item.priority, item.task)
}
})
} else {
self.queue.push({
priority: priority,
task: task
})
}
}