summaryrefslogtreecommitdiff
path: root/lib/internal/eachOfLimit.js
blob: 5e834637ed80f397e6079df0c682ee85355252ec (plain)
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
import noop from 'lodash/noop';
import once from './once';

import iterator from './iterator';
import onlyOnce from './onlyOnce';

export default function _eachOfLimit(limit) {
    return function (obj, iteratee, callback) {
        callback = once(callback || noop);
        obj = obj || [];
        var nextElem = iterator(obj);
        if (limit <= 0) {
            return callback(null);
        }
        var done = false;
        var running = 0;
        var errored = false;

        (function replenish () {
            if (done && running <= 0) {
                return callback(null);
            }

            while (running < limit && !errored) {
                var elem = nextElem();
                if (elem === null) {
                    done = true;
                    if (running <= 0) {
                        callback(null);
                    }
                    return;
                }
                running += 1;
                /* eslint {no-loop-func: 0} */
                iteratee(elem.value, elem.key, onlyOnce(function (err) {
                    running -= 1;
                    if (err) {
                        callback(err);
                        errored = true;
                    }
                    else {
                        replenish();
                    }
                }));
            }
        })();
    };
}