{"size": 1255, "ext": "js", "max_stars_repo_path": "node_modules/merkle-patricia-tree/prioritizedTaskExecutor.js", "max_stars_repo_name": "miguel567/nftgallery", "max_stars_repo_stars_event_min_datetime": "2020-06-22T07:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T05:09:10.000Z", "max_issues_repo_path": "node_modules/merkle-patricia-tree/prioritizedTaskExecutor.js", "max_issues_repo_name": "miguel567/nftgallery", "max_issues_repo_issues_event_min_datetime": "2021-09-16T04:33:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T17:45:51.000Z", "max_forks_repo_path": "node_modules/merkle-patricia-tree/prioritizedTaskExecutor.js", "max_forks_repo_name": "miguel567/nftgallery", "max_forks_repo_forks_event_min_datetime": "2020-08-10T09:10:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T22:08:35.000Z"}
{"max_stars_count": 107, "max_issues_count": 22, "max_forks_count": 34, "avg_line_length": 28.5227272727, "max_line_length": 112, "alphanum_fraction": 0.6749003984}
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
    })
  }
}
