diff --git a/doc/API.md b/doc/API.md index 24458fd..dd99f40 100644 --- a/doc/API.md +++ b/doc/API.md @@ -12,7 +12,7 @@ - [Channel([bufferLength = 0]) -> Channel](#channelbufferlength--0---channel) - [Channel.isChannel(value) -> Boolean](#channelischannelvalue---boolean) - [Channel.of(...values) -> Channel](#channelofvalues---channel) - - [Channel.from(callback | iterable | stream.Readable) -> Channel](#channelfromcallback--iterable--streamreadable---channel) + - [Channel.from(callback | iterable | stream.Readable[, mapfn [, thisArg]]) -> Channel](#channelfromcallback--iterable--streamreadable-mapfn--thisarg---channel) - [Channel Object](#channel-object) - [every(callbackfn[, thisArg]) -> async Boolean](#everycallbackfn-thisarg---async-boolean) - [filter(callbackfn[, thisArg]) -> Channel](#filtercallbackfn-thisarg---channel) @@ -164,7 +164,7 @@ Return `true` if `value` is a channel, `false` otherwise. Push `values` into a new channel and then close it. -### Channel.from(callback | iterable | stream.Readable) -> Channel +### Channel.from(callback | iterable | stream.Readable[, mapfn [, thisArg]]) -> Channel Create a new `Channel` from a callback function, an iterable, or a [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams). @@ -173,6 +173,9 @@ If given a callback function, call the function repeatedly to obtain values for pushing into the channel. Close the channel when the function returns `undefined`. +If the optional `mapfn` argument is provided, call it (using the also optional +`thisArg`) on each value before pushing it into the channel. + ## Channel Object ### every(callbackfn[, thisArg]) -> async Boolean diff --git a/lib/index.js b/lib/index.js index 66a71d8..72a8b38 100644 --- a/lib/index.js +++ b/lib/index.js @@ -306,7 +306,7 @@ const Channel = function(length = 0) { ); }; -Channel.from = values => { +Channel.from = (values, mapfn, thisArg) => { const channel = Channel(); (async () => { @@ -349,7 +349,7 @@ Channel.from = values => { } })(); - return channel; + return mapfn ? channel.map(mapfn, thisArg) : channel; }; Channel.of = (...values) => Channel.from(values); diff --git a/test/index.js b/test/index.js index 377bf3e..c9d74e0 100644 --- a/test/index.js +++ b/test/index.js @@ -55,6 +55,15 @@ describe(`Channel`, function() { assert.deepEqual(await Channel.from([0, 1, 2]).values(), [0, 1, 2]); }); + it(`mapfn`, async function() { + assert.deepEqual( + await Channel.from([`a`, `b`, `c`], value => + value.toUpperCase() + ).values(), + [`A`, `B`, `C`] + ); + }); + it(`Node.js's stream.readOnly`, async function() { const readOnly = stream.PassThrough({ objectMode: true }); readOnly.write(0);