buddy

node MVC discord bot
Log | Files | Refs | README

limiter.js (981B)


      1 'use strict';
      2 
      3 const kDone = Symbol('kDone');
      4 const kRun = Symbol('kRun');
      5 
      6 /**
      7  * A very simple job queue with adjustable concurrency. Adapted from
      8  * https://github.com/STRML/async-limiter
      9  */
     10 class Limiter {
     11   /**
     12    * Creates a new `Limiter`.
     13    *
     14    * @param {Number} concurrency The maximum number of jobs allowed to run
     15    *     concurrently
     16    */
     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    * @public
     31    */
     32   add(job) {
     33     this.jobs.push(job);
     34     this[kRun]();
     35   }
     36 
     37   /**
     38    * Removes a job from the queue and runs it if possible.
     39    *
     40    * @private
     41    */
     42   [kRun]() {
     43     if (this.pending === this.concurrency) return;
     44 
     45     if (this.jobs.length) {
     46       const job = this.jobs.shift();
     47 
     48       this.pending++;
     49       job(this[kDone]);
     50     }
     51   }
     52 }
     53 
     54 module.exports = Limiter;