From 7d0d203c2efd27047380fd7b193745d6910351c6 Mon Sep 17 00:00:00 2001 From: David Braun Date: Wed, 11 Oct 2017 21:50:59 -0400 Subject: [PATCH] Add `Channel.isChannel`. --- README.md | 4 ++++ lib/index.js | 14 +++++++++----- test/index.js | 5 +++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0b98100..67d2dc3 100644 --- a/README.md +++ b/README.md @@ -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 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 Pushes `values` into a new channel and then closes it. diff --git a/lib/index.js b/lib/index.js index a3769f6..53ee611 100644 --- a/lib/index.js +++ b/lib/index.js @@ -34,6 +34,8 @@ const Order = (channel) => { return {order, promise} } +const prototype = {} + const Channel = function (bufferLength = 0) { let buffered = 0 let closed = false @@ -102,7 +104,7 @@ const Channel = function (bufferLength = 0) { resolvedIndex -= index.push } - const readOnly = Object.freeze({ + const readOnly = Object.assign(Object.create(prototype), { every: async (callbackfn, thisArg) => { for (;;) { const value = await readOnly.shift() @@ -215,13 +217,12 @@ const Channel = function (bufferLength = 0) { })() return output - }, - - get value () { - return lastValue } }) + Object.defineProperty(readOnly, `value`, {get: () => lastValue}) + Object.freeze(readOnly) + const writeOnly = Object.freeze({ close: () => new Promise((resolve, reject) => { @@ -299,6 +300,9 @@ Channel.from = (values) => { Channel.of = (...values) => Channel.from(values) +Channel.isChannel = (arg) => + prototype.isPrototypeOf(arg) + Channel.select = (...methodPromises) => { const promise = new Promise((resolve, reject) => { methodPromises.forEach(async (promise) => { diff --git a/test/index.js b/test/index.js index 28d6b21..7856555 100644 --- a/test/index.js +++ b/test/index.js @@ -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 () { assert.deepEqual(await toArray(Channel.of(0, 1, 2)), [0, 1, 2]) })