Created
April 26, 2011 18:58
-
-
Save kkaefer/942859 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
var EventEmitter = require('events').EventEmitter; | |
module.exports = Queue; | |
function Queue(callback, concurrency) { | |
this.callback = callback; | |
this.concurrency = concurrency || 10; | |
this.next = this.next.bind(this); | |
this.invoke = this.invoke.bind(this); | |
this.queue = []; | |
this.running = 0; | |
} | |
util.inherits(Queue, EventEmitter); | |
Queue.prototype.add = function(item) { | |
this.queue.push(item); | |
if (this.running < this.concurrency) { | |
this.running++; | |
this.next(); | |
} | |
}; | |
Queue.prototype.invoke = function() { | |
if (this.queue.length) { | |
this.callback(this.queue.shift(), this.next); | |
} else { | |
this.next(); | |
} | |
}; | |
Queue.prototype.next = function(err) { | |
if (this.queue.length) { | |
process.nextTick(this.invoke); | |
} else { | |
this.running--; | |
if (!this.running) { | |
this.emit('empty'); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment