-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
67 lines (56 loc) · 1.1 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
/**
* Module dependencies.
*/
var Emitter = require('events').EventEmitter;
/**
* Expose `Queue`.
*/
module.exports = Queue;
/**
* Create a FIFO queue.
*
* @api public
*/
function Queue(){
this.buf = [];
this.fns = [];
this.max(Infinity);
this.events = new Emitter;
this.push = this.push.bind(this);
}
/**
* Push `data` onto the queue. Bound to `queue`.
*
* @param {Mixed} data
* @api public
*/
Queue.prototype.push = function(data){
if (this.fns.length) return this.fns.shift()(data);
if (this.buf.length == this._max) return this.events.emit('overflow', data);
this.buf.push(data);
};
/**
* Get the next piece of data.
*
* @return {Function}
* @api public
*/
Queue.prototype.next = function(){
var self = this;
return new Promise(function(resolve){
if (self.buf.length) return resolve(self.buf.shift());
self.fns.push(resolve);
});
};
/**
* Set the maximum buffer size.
*
* @param {Number} max
* @return {Queue}
* @api public
*/
Queue.prototype.max = function(max){
this._max = max;
if (this.buf.length > max) this.buf.length = max;
return this;
};