You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
981 B

  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 The maximum number of jobs allowed to run
  13. * 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. * @public
  28. */
  29. add(job) {
  30. this.jobs.push(job);
  31. this[kRun]();
  32. }
  33. /**
  34. * Removes a job from the queue and runs it if possible.
  35. *
  36. * @private
  37. */
  38. [kRun]() {
  39. if (this.pending === this.concurrency) return;
  40. if (this.jobs.length) {
  41. const job = this.jobs.shift();
  42. this.pending++;
  43. job(this[kDone]);
  44. }
  45. }
  46. }
  47. module.exports = Limiter;