Skip to content

Instantly share code, notes, and snippets.

@remy
Last active August 29, 2015 14:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remy/774bcfa196507946a91c to your computer and use it in GitHub Desktop.
Save remy/774bcfa196507946a91c to your computer and use it in GitHub Desktop.
Is this okay? The peek will just act as a benign through stream letting us see the first item. Would this add much overhead to the time do you think?
var peek = module.exports = function (fn) {
var peeked = false;
return through(function write(data) {
this.emit('data', data);
if (peeked) {
return;
}
peeked = true;
var stream = this;
var cont = function (end) {
if (end === true) {
stream.end();
} else {
stream.resume();
}
};
this.pause();
if (fn.length > 1) {
fn(data, cont);
} else {
cont(fn(data));
}
});
};
var array = new Pump(10);
array.pipe(peek(function (data) {
console.log('first item is', data); // 1
}));
array.pipe(slice(5)).on('data', collect(result)).on('end', function () {
t.equal(5, result.length);
t.end();
}));
@remy
Copy link
Author

remy commented Jun 25, 2015

Oh, the usage handles both sync and async usage. If the peek handler only receives data, then it's sync. But it can be async with:

peek(array, function (data, done) {
  // do something async with data
  done();  // continue stream, or `done(true)` to end the stream
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment