-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
70 lines (63 loc) · 1.65 KB
/
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
69
70
/*! run-parallel-limit. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
module.exports = runParallelLimit
const queueMicrotask = require('queue-microtask')
function runParallelLimit (tasks, limit, cb) {
if (typeof limit !== 'number') throw new Error('second argument must be a Number')
let results, len, pending, keys, isErrored
let isSync = true
let next
if (Array.isArray(tasks)) {
results = []
pending = len = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = len = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) queueMicrotask(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (err) isErrored = true
if (--pending === 0 || err) {
done(err)
} else if (!isErrored && next < len) {
let key
if (keys) {
key = keys[next]
next += 1
tasks[key](function (err, result) { each(key, err, result) })
} else {
key = next
next += 1
tasks[key](function (err, result) { each(key, err, result) })
}
}
}
next = limit
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.some(function (key, i) {
tasks[key](function (err, result) { each(key, err, result) })
if (i === limit - 1) return true // early return
return false
})
} else {
// array
tasks.some(function (task, i) {
task(function (err, result) { each(i, err, result) })
if (i === limit - 1) return true // early return
return false
})
}
isSync = false
}