-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (51 loc) · 1.77 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
var assert = require('assert');
// The exported function takes as input a function and returns a
// function returning a Promise that automatically delays calls to the
// original function such that the rate is kept below the specified
// number of calls in the specified number of milliseconds.
module.exports = function(f, calls, milliseconds) {
assert(f instanceof Function);
assert(typeof calls === 'number');
assert(typeof milliseconds === 'number');
var queue = [];
var complete = [];
var inflight = 0;
var processQueue = function() {
// Remove old complete entries.
var now = Date.now();
while (complete.length && complete[0] <= now - milliseconds)
complete.shift();
// Make calls from the queue that fit within the limit.
while (queue.length && complete.length + inflight < calls) {
var request = queue.shift();
++inflight;
// Call the deferred function, fulfilling the wrapper Promise
// with whatever results and logging the completion time.
var p = f.apply(request.this, request.arguments);
Promise.resolve(p).then((result) => {
request.resolve(result);
}, (error) => {
request.reject(error);
}).then(() => {
--inflight;
complete.push(Date.now());
if (queue.length && complete.length === 1)
setTimeout(processQueue, milliseconds);
});
}
// Check the queue on the next expiration.
if (queue.length && complete.length)
setTimeout(processQueue, complete[0] + milliseconds - now);
};
return function() {
return new Promise((resolve, reject) => {
queue.push({
this: this,
arguments: arguments,
resolve: resolve,
reject: reject
});
processQueue();
});
};
};