Last active
August 29, 2015 14:23
-
-
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?
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 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)); | |
} | |
}); | |
}; |
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 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(); | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: