Skip to content
Vitaly Tomilov edited this page Nov 15, 2021 · 54 revisions

Code examples

The library supports sufficient set of operators, to implement any other composite logic.

Find below some examples of such composite logic, plus custom operators.

Find the first matching element

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.

Slice logic

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 (iterator: Iterable<T>) => ({
        [Symbol.iterator](): Iterator<T> {
            const i = iterator[Symbol.iterator]();
            let index = 0;
            const s = start ?? 0;
            const e = end ?? Number.POSITIVE_INFINITY;
            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((_, index) => index === s),
    stop((_, index) => index === e - s)
);

console.log([...r]); //=> 4, 5, 6, 7
Clone this wiki locally