From 17a2688291182f75d3af6df4a477052acd785c95 Mon Sep 17 00:00:00 2001 From: David Braun Date: Wed, 11 Oct 2017 04:46:12 -0400 Subject: [PATCH] Add `every`. --- README.md | 16 ++++++++++++++++ lib/index.js | 14 ++++++++++++++ test/index.js | 6 ++++++ 3 files changed, 36 insertions(+) diff --git a/README.md b/README.md index 2ce2f9e..035e739 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,22 @@ Create a new `Channel` from an iterable or a [Node.js readable stream](https://n ### Channel Object +#### every (callbackfn[, thisArg]) -> async Boolean + +`callbackfn` should be a function that accepts one argument and returns a value +that is coercible to the Boolean values `true` or `false`. `every` calls +`callbackfn` once for each value present in the channel until it finds one where +`callbackfn` returns `false`. If such a value is found, every immediately +returns `false`. Otherwise, if `callbackfn` returned `true` for all elements, +`every` will return `true`. + +If a `thisArg` parameter is provided, it will be used as the `this` value for +each invocation of `callbackfn`. If it is not provided, `undefined` is used +instead. + +Unlike in the Array version of `every`, `callbackfn` is called with only one +argument. + #### filter(callbackfn[, thisArg]) -> Channel #### forEach(callbackfn[, thisArg]) -> async diff --git a/lib/index.js b/lib/index.js index 363c8d4..a3769f6 100644 --- a/lib/index.js +++ b/lib/index.js @@ -103,6 +103,20 @@ const Channel = function (bufferLength = 0) { } const readOnly = Object.freeze({ + every: async (callbackfn, thisArg) => { + for (;;) { + const value = await readOnly.shift() + + if (value === undefined) { + return true + } else { + if (!callbackfn.call(thisArg, value)) { + return false + } + } + } + }, + filter: (callbackfn, thisArg) => { const output = Channel() diff --git a/test/index.js b/test/index.js index 2022bdf..28d6b21 100644 --- a/test/index.js +++ b/test/index.js @@ -180,6 +180,12 @@ describe(`Channel object`, function () { }) }) + it(`every`, async function () { + const even = (number) => number % 2 === 0 + assert(!await Channel.of(0, 1, 2).every(even)) + assert(await Channel.of(0, 2, 4).every(even)) + }) + it(`filter`, async function () { assert.deepEqual( await toArray(Channel.of(0, 1, 2, 3, 4, 5)