-
Notifications
You must be signed in to change notification settings - Fork 5
Home
The library supports sufficient set of operators, to implement any other composite logic.
Find below some examples of such composite logic, plus custom operators.
import {pipe, filter, stop} from 'iter-ops';
const iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const r = pipe(
iterable,
filter(value => value === 5), // find value that matches 5
stop((_, index) => index > 0) // stop after the first element
);
console.log([...r]); //=> [5]
Since we are iterating into the first match only, we can simplify our code to just this:
const r = pipe(
iterable,
filter(value => value === 5) // find value that matches 5
);
console.log(r.first); //=> 5
Because we are explicitly requesting just the first element, the iteration will stop on the first match.
And if you replace filter
with start
operator above, the result will be the same.
Standard Array.slice supports negative start
and end
, to access elements relative to the end of the array.
For an iterable, you would have to convert it into an array first, which is why slice
wasn't
added to the library. But if we dispense with the negative inputs, we can implement it for any positive inputs,
as shown below.
import {Piper} from 'iter-ops';
export function slice<T>(start?: number, end?: number): Piper<T, T> {
return (iterable: Iterable<T>) => ({
[Symbol.iterator](): Iterator<T> {
const i = iterable[Symbol.iterator]();
const s = start ?? 0;
const e = end ?? Number.POSITIVE_INFINITY;
let index = 0;
return {
next(): IteratorResult<T> {
let a;
do {
a = i.next();
if (!a.done && index++ >= s && index <= e) {
return a;
}
} while (!a.done);
return {value: undefined, done: true};
}
};
}
});
}
Using our custom slice
operator below:
import {pipe} from 'iter-ops';
const iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const r = pipe(
iterable,
slice(3, 7)
);
console.log([...r]); //=> 4, 5, 6, 7
Note that you can get the same result with the start
and stop
operators:
import {pipe, start, stop} from 'iter-ops';
const iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const s = 3, e = 7; // start + stop indexes
const r = pipe(
iterable,
start((_, i) => i === s),
stop((_, i) => i === e - s)
);
console.log([...r]); //=> 4, 5, 6, 7
Here are some well-known operators, and their equivalents in this library.
-
skipUntil(condition)
=>start(condition)
-
skipWhile(condition)
=>start(!condition)
-
takeUntil(condition)
=>stop(condition)
-
takeWhile(condition)
=>stop(!condition)