CoolFace
Apppublic

strong-tie/inbound-calls

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
limiter.js56 linesDownload Raw Back to lib
1'use strict';2 3const kDone = Symbol('kDone');4const kRun = Symbol('kRun');5 6/**7 * A very simple job queue with adjustable concurrency. Adapted from8 * https://github.com/STRML/async-limiter9 */10class Limiter {11  /**12   * Creates a new `Limiter`.13   *14   * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed15   *     to run concurrently16   */17  constructor(concurrency) {18    this[kDone] = () => {19      this.pending--;20      this[kRun]();21    };22    this.concurrency = concurrency || Infinity;23    this.jobs = [];24    this.pending = 0;25  }26 27  /**28   * Adds a job to the queue.29   *30   * @param {Function} job The job to run31   * @public32   */33  add(job) {34    this.jobs.push(job);35    this[kRun]();36  }37 38  /**39   * Removes a job from the queue and runs it if possible.40   *41   * @private42   */43  [kRun]() {44    if (this.pending === this.concurrency) return;45 46    if (this.jobs.length) {47      const job = this.jobs.shift();48 49      this.pending++;50      job(this[kDone]);51    }52  }53}54 55module.exports = Limiter;56