This repository has been archived by the owner on Aug 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
60 lines (50 loc) · 1.31 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
'use strict'
// **Github:** https://github.com/thunks/thunk-workers
//
// **License:** MIT
const thunks = require('thunks')
const thunk = thunks()
module.exports = function thunkWorkers (count) {
const workers = new Workers(count)
return function workshop (task) {
return thunk.call(this, function (callback) {
if (typeof task !== 'function') {
return callback(new TypeError(`Task "${task}" is not function!`))
}
workers.add(new Job(this, task, callback)).exec()
})
}
}
function Workers (count) {
this.queue = []
this.pending = 0
this.count = count >= 1 ? Math.floor(count) : 1
}
Workers.prototype.add = function (job) {
this.queue.push(job)
return this
}
Workers.prototype.take = function () {
return this.queue.shift()
}
Workers.prototype.exec = function () {
if (this.pending >= this.count) return this
const ctx = this
const job = this.take()
if (!job) return this
this.pending++
thunk.delay.call(job.ctx)(() => job.task)(function () {
ctx.pending--
ctx.exec()
job.callback.apply(null, arguments)
})
}
function Job (ctx, task, callback) {
this.ctx = ctx
this.task = toThunkableFn(task)
this.callback = callback
}
function toThunkableFn (fn) {
if (thunks.isThunkableFn(fn)) return fn
return function (done) { thunk(fn.call(this))(done) }
}