From ce97802a8e83668b28eab7bde9a50639ac6a45c5 Mon Sep 17 00:00:00 2001 From: David Braun Date: Tue, 17 Oct 2017 11:02:12 -0400 Subject: [PATCH] Add `some`. --- doc/API.md | 18 ++++++++++++++++++ lib/index.js | 14 ++++++++++++++ test/index.js | 8 ++++++++ 3 files changed, 40 insertions(+) diff --git a/doc/API.md b/doc/API.md index 9929a95..30ddfad 100644 --- a/doc/API.md +++ b/doc/API.md @@ -23,6 +23,7 @@ - [reduce(callbackfn[, initialValue])](#reducecallbackfn-initialvalue) - [shift() -> async](#shift---async) - [slice(start[, end]) -> Channel](#slicestart-end---channel) + - [some(callbackfn[, thisArg])](#somecallbackfn-thisarg) - [Functional API](#functional-api) @@ -286,6 +287,23 @@ pushed. Unlike in `Array`'s method, `start` and `end` cannot be negative. +### some(callbackfn[, thisArg]) + +`callbackfn` should be a function that accepts one argument and returns a value +that is coercible to the Boolean values `true` or `false`. `some` calls +`callbackfn` once for each value in the channel until it finds one where +`callbackfn` returns `true`. If such a value is found, `some` immediately +returns `true`. Otherwise, `some` returns `false`. + +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 `Array`'s method, `callbackfn` is called with only one argument. + +`some` acts like the "exists" quantifier in mathematics. In particular, for an +empty channel, it returns `false`. + # Functional API There is a parallel API to support functional-style programming. Every channel diff --git a/lib/index.js b/lib/index.js index 7b5b077..4d0683c 100644 --- a/lib/index.js +++ b/lib/index.js @@ -225,6 +225,20 @@ const Channel = function(bufferLength = 0) { })(); return output; + }, + + some: async (callbackfn, thisArg) => { + for (;;) { + const value = await readOnly.shift(); + + if (value === undefined) { + return false; + } else { + if (callbackfn.call(thisArg, value)) { + return true; + } + } + } } }); diff --git a/test/index.js b/test/index.js index b3688b1..13294e9 100644 --- a/test/index.js +++ b/test/index.js @@ -336,6 +336,14 @@ describe(`Channel object`, function() { }); }); + it(`some`, async function() { + const even = value => value % 2 === 0; + const channel = Channel.of(0, 1, 2); + assert(await channel.some(even)); + assert.deepEqual(await toArray(channel), [1, 2]); + assert(!await Channel.of(1, 3, 5).some(even)); + }); + it(`value`, async function() { const channel = Channel(); (async () => {