Add some
.
This commit is contained in:
parent
78d26ef021
commit
ce97802a8e
3 changed files with 40 additions and 0 deletions
18
doc/API.md
18
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)
|
||||
|
||||
<!-- /TOC -->
|
||||
|
@ -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
|
||||
|
|
14
lib/index.js
14
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -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 () => {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue