# Code coverage report for async-throttle/index.js

## Statements: 100% (37 / 37) Branches: 92.86% (13 / 14) Functions: 100% (7 / 7) Lines: 100% (37 / 37) Ignored: none

All files » async-throttle/ » index.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68

    1
    7
    1

    6
    6
    6
    6
    6
    6

    1

    1
    3
    13
    13
    13

    1

    19

    1
    45
    6

    39
    13
    13
    13
    13

    39
    18
    6
    6

    1
    6
    6
    6

    1
    13
    13

    1
     'use strict';

    function Queue(options) {
      if (!(this instanceof Queue)) {
        return new Queue(options);
      }

      options = options || {};
      this.concurrency = options.concurrency || Infinity;
      this.pending = 0;
      this.jobs = [];
      this.cbs = [];
      this._done = done.bind(this);
    }

    var arrayAddMethods = [
      'push',
      'unshift',
      'splice'
    ];

    arrayAddMethods.forEach(function(method) {
      Queue.prototype[method] = function() {
        var methodResult = Array.prototype[method].apply(this.jobs, arguments);
        this._run();
        return methodResult;
      };
    });

    Object.defineProperty(Queue.prototype, 'length', {
      get: function() {
        return this.pending + this.jobs.length;
      }
    });

    Queue.prototype._run = function() {
      if (this.pending === this.concurrency) {
        return;
      }
      if (this.jobs.length) {
        var job = this.jobs.shift();
        this.pending++;
        job(this._done);
        this._run();
      }

      if (this.pending === 0) {
        while (this.cbs.length !== 0) {
          var cb = this.cbs.pop();
          process.nextTick(cb);
        }
      }
    };

    Queue.prototype.onDone = function(cb) {
      Eif (typeof cb === 'function') {
        this.cbs.push(cb);
        this._run();
      }
    };

    function done() {
      this.pending--;
      this._run();
    }

    module.exports = Queue;