Add Channel.isChannel.

This commit is contained in:
David Braun 2017-10-11 21:50:59 -04:00
parent 74f5673752
commit 7d0d203c2e
No known key found for this signature in database
GPG key ID: 5694EEC4D129BDCF
3 changed files with 18 additions and 5 deletions

View file

@ -173,6 +173,10 @@ These methods are similar to the equivalently named methods of `Array`.
Create a new `Channel` with an optional buffer. This allows an async function Create a new `Channel` with an optional buffer. This allows an async function
to push up to `bufferLength` values before blocking. to push up to `bufferLength` values before blocking.
#### Channel.isChannel(value) -> Boolean
Return `true` if `value` is a channel, `false` otherwise.
#### Channel.of(...values) -> Channel #### Channel.of(...values) -> Channel
Pushes `values` into a new channel and then closes it. Pushes `values` into a new channel and then closes it.

View file

@ -34,6 +34,8 @@ const Order = (channel) => {
return {order, promise} return {order, promise}
} }
const prototype = {}
const Channel = function (bufferLength = 0) { const Channel = function (bufferLength = 0) {
let buffered = 0 let buffered = 0
let closed = false let closed = false
@ -102,7 +104,7 @@ const Channel = function (bufferLength = 0) {
resolvedIndex -= index.push resolvedIndex -= index.push
} }
const readOnly = Object.freeze({ const readOnly = Object.assign(Object.create(prototype), {
every: async (callbackfn, thisArg) => { every: async (callbackfn, thisArg) => {
for (;;) { for (;;) {
const value = await readOnly.shift() const value = await readOnly.shift()
@ -215,13 +217,12 @@ const Channel = function (bufferLength = 0) {
})() })()
return output return output
},
get value () {
return lastValue
} }
}) })
Object.defineProperty(readOnly, `value`, {get: () => lastValue})
Object.freeze(readOnly)
const writeOnly = Object.freeze({ const writeOnly = Object.freeze({
close: () => close: () =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
@ -299,6 +300,9 @@ Channel.from = (values) => {
Channel.of = (...values) => Channel.of = (...values) =>
Channel.from(values) Channel.from(values)
Channel.isChannel = (arg) =>
prototype.isPrototypeOf(arg)
Channel.select = (...methodPromises) => { Channel.select = (...methodPromises) => {
const promise = new Promise((resolve, reject) => { const promise = new Promise((resolve, reject) => {
methodPromises.forEach(async (promise) => { methodPromises.forEach(async (promise) => {

View file

@ -57,6 +57,11 @@ describe(`Channel`, function () {
}) })
}) })
it(`isChannel`, function () {
assert(Channel.isChannel(Channel.of(0, 1, 2)))
assert(!Channel.isChannel(Array.of(0, 1, 2)))
})
it(`of`, async function () { it(`of`, async function () {
assert.deepEqual(await toArray(Channel.of(0, 1, 2)), [0, 1, 2]) assert.deepEqual(await toArray(Channel.of(0, 1, 2)), [0, 1, 2])
}) })