limiter.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const kDone = Symbol('kDone');
  3. const kRun = Symbol('kRun');
  4. /**
  5. * A very simple job queue with adjustable concurrency. Adapted from
  6. * https://github.com/STRML/async-limiter
  7. */
  8. class Limiter {
  9. /**
  10. * Creates a new `Limiter`.
  11. *
  12. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  13. * to run concurrently
  14. */
  15. constructor(concurrency) {
  16. this[kDone] = () => {
  17. this.pending--;
  18. this[kRun]();
  19. };
  20. this.concurrency = concurrency || Infinity;
  21. this.jobs = [];
  22. this.pending = 0;
  23. }
  24. /**
  25. * Adds a job to the queue.
  26. *
  27. * @param {Function} job The job to run
  28. * @public
  29. */
  30. add(job) {
  31. this.jobs.push(job);
  32. this[kRun]();
  33. }
  34. /**
  35. * Removes a job from the queue and runs it if possible.
  36. *
  37. * @private
  38. */
  39. [kRun]() {
  40. if (this.pending === this.concurrency) return;
  41. if (this.jobs.length) {
  42. const job = this.jobs.shift();
  43. this.pending++;
  44. job(this[kDone]);
  45. }
  46. }
  47. }
  48. module.exports = Limiter;