Last active
December 23, 2015 01:09
-
-
Save parshap/6558981 to your computer and use it in GitHub Desktop.
Rate limited map-stream
This file contains 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 es = require("event-stream"); | |
// Wraps a map-stream to only process *limit* chunks at a time | |
module.exports = function(mapStream, limit) { | |
var waiting = 0, ended = false, buffer = []; | |
var stream = es.through(write, function() { | |
ended = true; | |
maybeEnd(); | |
}); | |
function write(data) { | |
if (waiting >= limit) { | |
buffer.push(data); | |
} | |
else { | |
waiting += 1; | |
mapStream.write(data); | |
} | |
} | |
function unbuffer() { | |
if (buffer.length && waiting < limit) { | |
write(buffer.shift()); | |
} | |
} | |
function maybeEnd() { | |
if (ended && waiting === 0) { | |
stream.emit("end"); | |
} | |
} | |
mapStream.on("data", function(data) { | |
stream.emit("data", data); | |
waiting -= 1; | |
unbuffer(); | |
maybeEnd(); | |
}); | |
return stream; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment