@sweet-monads/iterator v3.3.1
@sweet-monads/iterator
Iterator additional methods, Iterator lazy helper methods implementation
This library belongs to sweet-monads project
sweet-monads — easy-to-use monads implementation with static types definition and separated packages.
- No dependencies, one small file
- Easily auditable TypeScript/JS code
- Check out all libraries: either, iterator, interfaces, maybe identity
Why?
All of these methods (except methods which return non-LazyIterator values) are lazy. They will only consume the iterator when they need the next item from it.
import LazyIterator from "@sweet-monads/iterator";
// array from 1 to 10000
const longArray = Array.from({ length: 10000 }).map((_, i) => i + 1);
const lazyArray = LazyIterator.from<number>(longArray);
// ~ 25_000 iterations
const sum1 = longArray
.filter(i => i % 2)
.map(i => i * i)
.filter(i => i % 3)
.reduce((sum, i) => sum + i, 0);
// 10_000 iterations
const sum2 = lazyArray
.filter(i => i % 2)
.map(i => i * i)
.filter(i => i % 3)
.sum();Usage
npm install @sweet-monads/iterator
import LazyIterator from "@sweet-monads/iterator";
const lazyArray = LazyIterator.from<number>([1, 2, 3, 4, 5]);
const newArray = lazyArray.map(a => a * a).collect();API
LazyIterator.from(iterable)LazyIterator#allLazyIterator#anyLazyIterator#chainLazyIterator#countLazyIterator#cycleLazyIterator#enumarateLazyIterator#foldLazyIterator#firstLazyIterator#filterLazyIterator#filterMapLazyIterator#findLazyIterator#findMapLazyIterator#flatMapLazyIterator#flattenLazyIterator#forEachLazyIterator#lastLazyIterator#mapLazyIterator#maxLazyIterator#minLazyIterator#nthLazyIterator#partionLazyIterator#positionLazyIterator#productLazyIterator#reverseLazyIterator#scanLazyIterator#skipLazyIterator#skipWhileLazyIterator#stepByLazyIterator#sumLazyIterator#takeLazyIterator#takeWhileLazyIterator#unzipLazyIterator#zipLazyIterator#compressLazyIterator#permutationsLazyIterator#sliceLazyIterator#compactLazyIterator#containsLazyIterator#uniqueLazyIterator#isEmptyLazyIterator#exceptLazyIterator#intersectLazyIterator#prependLazyIterator#appendLazyIterator#collect
LazyIterator.from
Create LazyIterator<I> from any Iterable<I> object
function from<I>(iterable: Iterable<I>): LazyIterator<I>;
function from<I>(iterable: Iterable<I> & { fromIterator: FromIterator<I> }): LazyIterator<I>;
function from<I>(iterable: Iterable<I>, fromIterator: FromIterator<I>): LazyIterator<I>;iterable: Iterable<I>- Iterable object which will be wrapped byLazyIteratorfromIterator: () => Iterable<I>(default isfunction() { return [...this] }) - function which define conversion fromLazyIteratorto iterable object (default isArray), it could be defined insideiterableobject.- Returns
LazyIteratorwhich contains all elements fromiterable
Example:
LazyIterator.from<number>([1, 2, 3]); // LazyIterator<number>
LazyIterator.from([1, 2, 3]); // LazyIterator<number>LazyIterator.all
Tests if every element of the LazyIterator matches a predicate.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function all<I>(predicate: (i: I) => boolean): boolean;predicate: (i: I) => boolean- takes a function that returnstrueorfalse. It applies this function to each element of the iterator, and if they all returntrue, then so doesall(). If any of them returnfalse, it returnsfalse.Returns
trueifpredicatereturntruefor all elements ofLazyIteratororLazyIteratoris empty otherwisefalse
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
iterator.all(a => typeof a === "number"); // true
iterator.all(a => a % 2 === 0); // falseLazyIterator.any
Tests if any element of the LazyIterator a predicate.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function any<I>(predicate: (i: I) => boolean): boolean;predicate: (i: I) => boolean- takes a function that returnstrueorfalse. It applies this function to each element of the iterator, and if any of them returntrue, then so doesany(). If they all returnfalse, it returnsfalse.- Returns
trueif exist element fromLazyIteratorfor whichpredicatereturntrueotherwisefalseExample:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
iterator.any(a => a % 2 === 0); // true
iterator.any(a => a === 0); // falseLazyIterator.chain
Takes two iterators and creates a new iterator over both in sequence.
function chain<I>(...otherIterators: Array<Iterable<I>>): LazyIterator<I>;iterables: Array<Iterable<I>>- array of iterable objects with same type which should be merged in one- Returns a new
LazyIteratorwhich will first iterate over values from the firstLazyIteratorand then over values from the second iterator.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const newIterator = iterator.chain([6, 7]);
for (const i of newIterator) {
console.log(i);
}
// 1
// 2
// 3
// 4
// 5
// 6
// 7LazyIterator.count
Consumes the iterator, counting the number of iterations and returning it.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function count(): number;- Returns count of elements in
LazyIterator
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const infinityIterator = new LazyIterator(function* () {
while (true) yield 0;
});
iterator.count(); // 5
infinityIterator.count(); // Will lock your applicationLazyIterator.cycle
Instead of stopping at done: true, the LazyIterator will instead start again, from the beginning. After iterating again, it will start at the beginning again. And again. And again. Forever.
function cycle<I>(): LazyIterator<I>;- Returns repeated an
LazyIteratorendlessly if it is not empty.
Example:
const iterator = LazyIterator.from([1, 2, 3]).cycle();
const empty = LazyIterator.from([]).cycle();
let i = iterator[Symbol.iterator]();
i.next().value; // 1
i.next().value; // 2
i.next().value; // 3
i.next().value; // 1
i.next().value; // 2
i.next().value; // 3
i.next().value; // 1
let i = empty[Symbol.iterator]();
i.next().done; // true
for (const a of iterator); // Will lock your application
for (const a of empty); // Will not computedLazyIterator.enumarate
Creates an LazyIterator which gives the current iteration count as well as the next value.
function enumarate<I>(): LazyIterator<[number, I]>;- Returns the
LazyIteratorwhich yields pairs(i, val), whereiis the current index of iteration andvalis the value returned by the iterator.
Example:
const iterator = LazyIterator.from([6, 7, 8, 9]).enumerate();
for (const [index, element] of iterator) {
console.log(index, element);
}
// 0, 6
// 1, 7
// 2, 8
// 3, 9LazyIterator.fold
An LazyIterator method that applies a function as long as it returns successfully, producing a single, final value. Folding is useful whenever you have a collection of something, and want to produce a single value from it.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function fold<I>(fn: (a: I, i: I) => I): I;
function fold<I, A>(fn: (a: A, i: I) => A, accumulator: A): A;fn: (a: A, i: I) => A- accumulator function which fold elements in some valueaccumulator: A(defaultLazyItertor#first()) - the initial value thefnwill have on the first call.- Returns value which are computed by invocation of
fnwith each element of theLazyIteratorandaccumulatorwhich was computed at previous step of iteration.
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const sum = iterator.fold((sum, i) => sum + i, 0); // number 20LazyIterator.first
An LazyIterator method that return first element of the LazyIterator.
Info: more information about Maybe
function first(): Maybe<I>;
function first(withoutMaybe: false): Maybe<I>;
function first(withoutMaybe: true): I | undefined;withoutMaybe(defaultfalse) - regulate return type, iftrueresult will be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns
Maybe<I>.Just(orIifwithoutMaybeistrue) ifLazyIteratoris not empty otherwiseMaybe<I>.None(ofundefinedifwithoutMaybeistrue)
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const empty = LazyIterator.from([]);
const f1 = iterator.first(); // Maybe<number>.Just with value 1
const f2 = iterator.first(false); // Maybe<number>.Just with value 1
const f3 = iterator.first(true); // 1
const f4 = empty.first(); // Maybe<number>.None without value
const f5 = empty.first(false); // Maybe<number>.None without value
const f6 = empty.first(true); // undefinedLazyIterator.filter
Creates an LazyIterator which uses a function to determine if an element should be yielded.
function filter<I, T extends I>(predicate: (i: I) => i is T): LazyIterator<T>;
function filter<I>(predicate: (i: I) => boolean): LazyIterator<I>;predicate: (i: I) => boolean- function which must returntrueorfalse.- Returns
LazyIterator<T>which callsfnfunction on each element. Iffnreturnstrue, then the element is returned. Iffnreturnsfalse, it will try again, and callfnon the next element, seeing if it passes the test.
Example:
const iterator = LazyIterator.from([1, 2, 2, 3, 4, 5, 6, 7, 8, 9]);
const filtered = iterator.filter(i => i % 2); // LazyIterator<number>
const twos = iterator.filter((i): i is 2 => i === 2); // LazyIterator<2>
for (const i of filtered) console.log(i);
// 1
// 3
// 5
// 7
// 9
for (const i of twos) console.log(i);
// 2
// 2LazyIterator.filterMap
Creates an iterator that both filters and maps.
Info: more information about Maybe
function filterMap<I, T>(predicateMapper: (i: I) => Maybe<T>): LazyIterator<T>;
function filterMap<I, T>(predicateMapper: (i: I) => T | undefined): LazyIterator<T>;predicateMapper: (i: I) => Maybe<T> | T | undefined- function which must return anMaybe<T>orT | undefinedifwithoutMaybeistrue.- Returns
LazyIteratorwhich callspredicateMapperon each element. IfpredicateMapperreturnsjust(element), then that element is returned. IfpredicateMapperreturnsnone, it will try again, and callpredicateMapperon the next element, seeing if it will returnjust.
Example:
const iterator = LazyIterator.from([1, 2, 2, 3, 4, 5, 6, 7, 8, 9]);
const filtered = iterator.filterMap(i => (i % 2 ? just(i * i) : none())); // LazyIterator<number>
// filtered1 <-> [1, 9, 25, 49, 81]LazyIterator.find
Searches for an element of an LazyIterator that satisfies a predicate.
find() is short-circuiting; in other words, it will stop processing as soon as the predicate returns true. But, it will lock your application if your LazyIterator is cycled and doesn't contain element which will satisfied a predicate.
Info: more information about Maybe
function find<I>(predicate: (i: I) => boolean): Maybe<I>;
function find<I>(predicate: (i: I) => boolean, withoutMaybe: false): Maybe<I>;
function find<I>(predicate: (i: I) => boolean, withoutMaybe: true): I | undefined;predicate: (i: I) => boolean- function that returntrueorfalse.withoutMaybe(defaultfalse) - regulate return type iftrueresult should be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns
Maybe<I>.Just(orIifwithoutMaybeistrue) ifLazyIteratoris not empty and contain element for whichpredicatereturntrueotherwiseMaybe<I>.None(ofundefinedifwithoutMaybeistrue)
Example:
const iterator = LazyIterator.from([1, 2, 2, 3, 4, 5, 6, 7, 8, 9]);
const two1 = iterator.find(i => i === 2); // Maybe<number>.Just with value 2
const two2 = iterator.find(i => i === 2, false); // Maybe<number>.Just with value 2
const two3 = iterator.find(i => i === 2, true); // 2
const two4 = iterator.find(i => i === 10); // Maybe<number>.None without value
const two5 = iterator.find(i => i === 10, false); // Maybe<number>.None without value
const two6 = iterator.find(i => i === 10, true); // undefinedLazyIterator.findMap
Applies function to the elements of LazyIterator and returns the first non-none result.
findMap() is short-circuiting; in other words, it will stop processing as soon as the predicate returns Maybe.Just or non-undefined value. But, it will lock your application if your LazyIterator is cycled and doesn't contain element which will satisfied a predicate.
Info: more information about Maybe
function findMap<I, T>(predicateMapper: (i: I) => Maybe<T> | T | undefined): Maybe<I>;
function findMap<I, T>(predicateMapper: (i: I) => Maybe<T> | T | undefined, withoutMaybe: false): Maybe<T>;
function findMap<I, T>(predicateMapper: (i: I) => Maybe<T> | T | undefined, withoutMaybe: true): I | undefined;predicateMapper: (i: I) => Maybe<T> | T | undefined- predicate mapper function which returnMaybe<T>orT | undefined.withoutMaybe(defaultfalse) - regulate return type ofpredicateMapper, iftrueresult should be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns mapped by
predicateMapperMaybe<I>.Just(orIifwithoutMaybeistrue) ifLazyIteratoris not empty and contain element for whichpredicateMapperreturnMaybe<I>.Just(or notundefinedifwithoutMaybeistrue) otherwiseMaybe<I>.None(ofundefinedifwithoutMaybeistrue)
Example:
const iterator = LazyIterator.from([1, 2, 2, 3, 4, 5, 6, 7, 8, 9]);
const two1 = iterator.find(i => (i === 2 ? just(i) : none())); // Maybe<number>.Just
const two2 = iterator.find(i => (i === 2 ? just(i) : none()), false); // Maybe<number>.Just
const two3 = iterator.find(i => (i === 2 ? i : undefined), true); // 2
const two4 = iterator.find(i => (i === 10 ? just(i) : none())); // Maybe<number>.None
const two5 = iterator.find(i => (i === 10 ? just(i) : none()), false); // Maybe<number>.None
const two6 = iterator.find(i => (i === 10 ? i : undefined), true); // undefinedLazyIterator.flatMap
Creates an LazyIterator that works like map, but flattens nested structure.
function flatMap<I, N>(fn: (i: I) => LazyIterator<N>): LazyIterator<N>;fn: (i: I) => LazyIterator<N>- mapper function which returnLazyIterator<N>- Returns flattened
LazyIterator<N>
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const mapped = iterator.flatMap(n => LazyIterator.from<string>("|".repeat(n)));
for (const i of mapped) console.log(i);
// 15 times "|"LazyIterator.flatten
Creates an LazyIterator that flattens nested structure.
This is useful when you have an LazyIterator of LazyIterator or an LazyIterator of things that can be turned into iterators and you want to remove one level of indirection.
function flatten<I>(this: LazyIterator<I | LazyIterator<I>>): LazyIterator<I>;this: LazyIterator<I | LazyIterator<I>>-thiscontext should be presented asLazyIteratorofLazyIteratorofIitems.- Returns flattened at 1 level
LazyIterator<I>
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const mapped = iterator.map(n => LazyIterator.from<string>("|".repeat(n))); // LazyIterator<LazyIterator<string>>;
const flatten = mapped.flatten(); // LazyIterator<string>LazyIterator.forEach
Calls a function on each element of an LazyIterator.
This is equivalent to using a for..of loop on the LazyIterator, although break and continue are not possible from a function. It's generally more idiomatic to use a for..of loop, but forEach may be more legible when processing items at the end of longer LazyIterator chains.
function forEach<I>(fn: (i: I) => unknown): void;fn: (i: I) => unknown- function which will be invoked with each element ofLazyIterator<I>Returns
undefinedExample:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
iterator.forEach(console.log);
// 1
// 2
// 3
// 4
// 5LazyIterator.last
An LazyIterator method that return last element of the LazyIterator.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
Info: more information about Maybe
function last<I>(): Maybe<I>;
function last<I>(withoutMaybe: false): Maybe<I>;
function last<I>(withoutMaybe: true): I | undefined;withoutMaybe(defaultfalse) - regulate return type, iftrueresult will be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns
Maybe<I>.Just(orIifwithoutMaybeistrue) ifLazyIteratoris not empty otherwiseMaybe<I>.None(ofundefinedifwithoutMaybeistrue)
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const empty = LazyIterator.from([]);
const cycled = LazyIterator.from([1, 2]).cycle();
const f1 = iterator.last(); // Maybe<number>.Just with value 8
const f2 = iterator.last(false); // Maybe<number>.Just with value 8
const f3 = iterator.last(true); // 8
const f4 = empty.last(); // Maybe<number>.None without value
const f5 = empty.last(false); // Maybe<number>.None without value
const f6 = empty.last(true); // undefined
const f7 = cycled.last(true); // Lock your applicationLazyIterator.map
Takes a function and creates an LazyIterator which calls that function on each element. map() transforms one LazyIterator into another.
If you are good at thinking in types, you can think of map() like this: If you have an LazyIterator that gives you elements of some type I, and you want an LazyIterator of some other type T, you can use map(), passing a function that takes an I and returns a T.
function map<I, T>(fn: (i: I) => T): LazyIterator<T>;fn: (i: I) => T- function which will called with each element ofLazyIterator- Returns
LazyIteratorwhich contains all values which was transformed byfn
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const mapped = iterator.map(a => a.toString()); // LazyIterator<string>
for (const i of mapped) console.log(i);
// "1"
// "1"
// "2"
// "3"
// "5"
// "8"LazyIterator.max
Returns the maximum element of an LazyIterator.
If several elements are equally maximum, the last element is returned.
function max<I>(f?: (i: I) => number): Maybe<I>;
function max<I>(f: (i: I) => number, withoutMaybe: false): Maybe<I>;
function max<I>(f: (i: I) => number, withoutMaybe: true): I | undefined;fn: (i: I) => T- function which will convert itemiinnumber.withoutMaybe(defaultfalse) - regulate return type, iftrueresult will be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns maximum element of in
LazyIterator. If theLazyIteratoris empty,Maybe<number>.Nonewill be returned (orundefinedifwithoutMaybeistrue).
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const empty = LazyIterator.from([]);
iterator.max(); // Maybe<number>.Just with value 8
iterator.max(a => a); // Maybe<number>.Just with value 8
iterator.max(a => a, false); // Maybe<number>.Just with value 8
iterator.max(a => a, true); // 8
empty.max(); // Maybe<number>.None without value
empty.max(a => a); // Maybe<number>.None without value
empty.max(a => a, false); // Maybe<number>.None without value
empty.max(a => a, true); // undefinedLazyIterator.min
Returns the minimum element of an LazyIterator.
If several elements are equally minimum, the first element is returned.
function min<I>(f?: (i: I) => number): Maybe<I>;
function min<I>(f: (i: I) => number, withoutMaybe: false): Maybe<I>;
function min<I>(f: (i: I) => number, withoutMaybe: true): I | undefined;fn: (i: I) => T- function which will convert itemiinnumber.withoutMaybe(defaultfalse) - regulate return type, iftrueresult will be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns minimum element of in
LazyIterator. If theLazyIteratoris empty,Maybe<number>.Nonewill be returned (orundefinedifwithoutMaybeistrue).
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const empty = LazyIterator.from([]);
iterator.min(); // Maybe<number>.Just with value 1
iterator.min(a => a); // Maybe<number>.Just with value 1
iterator.min(a => a, false); // Maybe<number>.Just with value 1
iterator.min(a => a, true); // 1
empty.min(); // Maybe<number>.None without value
empty.min(a => a); // Maybe<number>.None without value
empty.min(a => a, false); // Maybe<number>.None without value
empty.min(a => a, true); // undefinedLazyIterator.nth
Returns the nth element of the LazyIterator.
Like most indexing operations, the count starts from zero, so nth(0) returns the first value, nth(1) the second, and so on.
function nth<I>(n: number): Maybe<I>;
function nth<I>(n: number, withoutMaybe: false): Maybe<I>;
function nth<I>(n: number, withoutMaybe: true): I | undefined;n: number- position of element inLazyIteratorwithoutMaybe(defaultfalse) - regulate return type, iftrueresult will be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns the
nth element of theLazyIterator. Ifnis greater than or equals toLazyIterator#countorLazyIteratoris empty,Maybe<number>.Nonewill be returned (orundefinedifwithoutMaybeistrue).
Example:
const iterator = LazyIterator.from([1, 1, 2, 3, 5, 8]);
const empty = LazyIterator.from([]);
iterator.nth(0); // Maybe<number>.Just with value 1
iterator.nth(0, false); // Maybe<number>.Just with value 1
iterator.nth(0, true); // 1
iterator.nth(6); // Maybe<number>.None without value
iterator.nth(6, false); // Maybe<number>.None without value
iterator.nth(6, true); // undefined
empty.nth(0); // Maybe<number>.None without value
empty.nth(0, false); // Maybe<number>.None without value
empty.nth(0, true); // undefinedLazyIterator.partion
Returns a 2-elements tuple of arrays. Splits the elements in the input iterable into either of the two arrays. Will fully exhaust the input iterable. The first array contains all items that match the predicate, the second the rest
function partion<I, T extends I>(predicate: (i: I) => i is T): [T[], I[]];
function partion<I>(predicate: (i: I) => boolean): [I[], I[]];predicate: (i: I) => boolean- function which must returntrueorfalse.- Returns a 2-elements tuple of arrays which contains elements which satisfy
predicate(first array) and which not (second array)
Example:
const iterator = LazyIterator.from([1, 2, 2, 3, 4, 5, 6, 7, 8, 9]);
const [filtered, rest] = iterator.partion(i => i % 2); // [number[], number[]]
const [twos, notTwos] = iterator.partion((i): i is 2 => i === 2); // [2[], number[]]
for (const i of filtered) console.log(i);
// 1
// 3
// 5
// 7
// 9
for (const i of rest) console.log(i);
// 2
// 2
// 4
// 6
// 8
for (const i of twos) console.log(i);
// 2
// 2
for (const i of notTwos) console.log(i);
// 1
// 3
// 4
// 5
// 6
// 7
// 8
// 9LazyIterator.position
Searches for an element in an iterator, returning its index.
position() is short-circuiting; in other words, it will stop processing as soon as the predicate returns true. But, it will lock your application if your LazyIterator is cycled and doesn't contain element which will satisfied a predicate.
Info: more information about Maybe
function position<I>(predicate: (i: I) => boolean): Maybe<number>;
function position<I>(predicate: (i: I) => boolean, withoutMaybe: false): Maybe<number>;
function position<I>(predicate: (i: I) => boolean, withoutMaybe: true): number | undefined;predicate: (i: I) => boolean- function that returntrueorfalse.withoutMaybe(defaultfalse) - regulate return type iftrueresult should be "undefinable" item type elseMaybe<I>which could be presented asJustvalue orNone.- Returns
Maybe<I>.Just(orIifwithoutMaybeistrue) ifLazyIteratoris not empty and contain element for whichpredicatereturntrueotherwiseMaybe<I>.None(ofundefinedifwithoutMaybeistrue)
Example:
const iterator = LazyIterator.from([1, 2, 2, 3, 4, 5, 6, 7, 8, 9]);
const two1 = iterator.position(i => i === 2); // Maybe<number>.Just with value 1
const two2 = iterator.position(i => i === 2, false); // Maybe<number>.Just with value 1
const two3 = iterator.position(i => i === 2, true); // 1
const two4 = iterator.position(i => i === 10); // Maybe<number>.None without value
const two5 = iterator.position(i => i === 10, false); // Maybe<number>.None without value
const two6 = iterator.position(i => i === 10, true); // undefinedLazyIterator.product
Iterates over the entire iterator, multiplying all the elements.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function product(this: LazyIterator<number>): number;this: LazyIterator<number>-LazyIteratorshould containnumberelements- Returns product of each elements in
LazyIterator. An emptyLazyIteratorreturns the one value of the type.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const empty = LazyIterator.from([]);
const cycled = LazyIterator.from([1]).cycle();
const product1 = iterator.product(); // 120
const product2 = empty.product(); // 1
const product3 = cycled.product(); // Will lock your applicationLazyIterator.reverse
Reverses an iterator's direction. Usually, LazyIterators iterate from left to right. After using reverse(), an LazyIterator will instead iterate from right to left.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function reverse<I>(): LazyIterator<I>;- Returns reverse
LazyIterator
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const cycled = LazyIterator.from([1]).cycle();
const reversed1 = iterator.reverse();
for (const a of reversed1) console.log(a);
// 1
// 2
// 3
// 4
// 5
const reversed2 = cycled.reverse(); // Will lock your applicationLazyIterator.scan
An LazyIterator adaptor similar to LazyIterator#fold that holds internal state and produces a new iterator.
function scan<A, I>(fn: (a: A, i: I) => A, accumulator: A): A;fn: (a: A, i: I) => A- a function with two arguments, the first being the internal state and the second anLazyIteratorelement. The function can assign to the internal state to share state between iterations.accumulator: A- an initial value which seeds the internal state- Returns the
LazyIteratorwhich yieldsaccumulatorper each iteration which computed byfninvocation.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const factorials = iterator.scan((a, i) => a * i, 1);
for (const a of factorials) console.log(a);
// 1
// 2
// 6
// 24
// 120LazyIterator.skip
Creates an LazyIterator that skips the first n elements.
After they have been consumed, the rest of the elements are yielded.
function skip<I>(n: number): LazyIterator<I>;n: number- count of element which should be skipped.- Returns the
LazyIteratorwhich yields all elements afternelements.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const skipped = iterator.skip(2);
for (const a of skipped) console.log(a);
// 3
// 4
// 5LazyIterator.skipWhile
Creates an LazyIterator that LazyIterator#skip s elements based on a predicate.
function skipWhile<I>(predicate: (i: I) => boolean): LazyIterator<I>;predicate: (i: I) => boolean- function which will be called on each element of theLazyIterator, and ignore elements until it returnsfalse.- Returns the
LazyIteratorwhich yields the rest of the elements after firstfalsefrompredicateinvocation.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const skipped = iterator.skipWhile(a => a <= 2);
for (const a of skipped) console.log(a);
// 3
// 4
// 5LazyIterator.stepBy
Creates an LazyIterator starting at the same point, but stepping by the given amount at each iteration.
Note: The first element of the LazyIterator will always be returned, regardless of the step given.
Note: If step will be less than 1 then method will throw an Error.
function stepBy<I>(step: number): LazyIterator<I>;step: number- number (greater than 0) of each element which should be yielded.- Returns the
LazyIteratorstarting at the same point, but stepping by the given amount at each iteration.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const skipped = iterator.stepBy(2);
for (const a of skipped) console.log(a);
// 1
// 3
// 5LazyIterator.sum
Sums the elements of an iterator. Takes each element, adds them together, and returns the result.
Warning: Be careful, LazyIterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function sum(this: LazyIterator<number>): number;this: LazyIterator<number>-LazyIteratorshould containnumberelements- Returns sum of each elements in
LazyIterator. An emptyLazyIteratorreturns the zero value of the type.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const empty = LazyIterator.from([]);
const cycled = LazyIterator.from([1]).cycle();
const product1 = iterator.sum(); // 15
const product2 = empty.sum(); // 0
const product3 = cycled.sum(); // Will lock your applicationLazyIterator.take
Creates an LazyIterator that yields its first n elements.
function take<I>(n: number): LazyIterator<I>;n: number- count of element which should be taken.- Returns the
LazyIteratorwhich yields firstnelements.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const skipped = iterator.take(2);
for (const a of skipped) console.log(a);
// 1
// 2LazyIterator.takeWhile
Creates an LazyIterator that LazyIterator#take s elements based on a predicate.
function takeWhile<I>(predicate: (i: I) => boolean): LazyIterator<I>;predicate: (i: I) => boolean- function which will be called on each element of theLazyIterator, and yield elements until it returnsfalse.- Returns the
LazyIteratorwhich yields elements before firstfalsefrompredicateinvocation.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
const skipped = iterator.takeWhile(a => a <= 2);
for (const a of skipped) console.log(a);
// 1
// 2LazyIterator.unzip
Converts an LazyIterator of pairs into a pair of arrays.
unzip() consumes an entire LazyIterator of pairs, producing two arrays: one from the left elements of the pairs, and one from the right elements.
This function is, in some sense, the opposite of LazyIterator#zip.
function unzip<A, B>(this: LazyIterator<[A, B]>): [A[], B[]];this: LazyIterator<[A, B]>- theLazyIteratorwhich will be an context of the function should contain pair(array with two elements) as element.- Returns two arrays: first contains elements from the left elements of the pairs, and second contains elements from the right elements.
Example:
const iterator = LazyIterator.from([
[1, 2],
[3, 4],
[5, 6],
[7, 8]
]);
const [odd, even] = iterator.unzip();
odd; // [1, 3, 5, 7]
even; // [2, 4, 6, 8]LazyIterator.zip
'Zips up' two iterators into a single LazyIterator of pairs.
function zip<I, T>(other: LazyIterator<T>): LazyIterator<[I, T]>;other: LazyIterator<T>- theLazyIteratorwhich elements will be the right element of each yielded pair(array with two elements).- Returns
LazyIteratorthat will iterate over two otherLazyIterators, returning a pair(array with two elements) where the first element comes from the firstLazyIterator(which was context for the method), and the second element comes from the secondLazyIterator(which came from argument).
Example:
const iterator1 = LazyIterator.from([1, 3, 5, 7]);
const iterator2 = LazyIterator.from([2, 4, 6, 8]);
const iterator3 = LazyIterator.from([15]);
const zipped1 = iterator1.zip(iterator2);
const zipped2 = iterator1.zip(iterator3);
for (const a of zipped1) console.log(a);
// [1, 2]
// [3, 4]
// [5, 6]
// [7, 8]
for (const a of zipped2) console.log(a);
// [1, 15]LazyIterator.compress
Pick items for LazyIterator by mask which will be provided as argument.
function compress<I>(mask: number[] | boolean[]): LazyIterator<I>;mask: boolean[] | number[]- mask which determine which elements will be yielded by newLazyIterator.- Returns
LazyIteratorthat filters elements from data returning only those that have a corresponding element in selectors that evaluates to true. Stops when either the data or selectors iterables has been exhausted.
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const masked1 = iterator.compress([0, 0, 1, 1, 1, 0, 1]);
const masked2 = iterator.compress([false, false, true, true, true, false, true]);
for (const a of masked1) console.log(a);
// 3
// 4
// 5
// 7
for (const a of masked2) console.log(a);
// 3
// 4
// 5
// 7LazyIterator.permutations
Return successive permutations of elements in the iterable.
function permutations<I>(): LazyIterator<[I, I]>;- Returns
LazyIteratorthat yield pair (array with two elements) which contains combination of each elements.
Example:
const iterator = LazyIterator.from([1, 2, 3]);
const permutated = iterator.permutations();
for (const a of permutated) console.log(a);
// [1, 2]
// [1, 3]
// [2, 1]
// [2, 3]
// [3, 1]
// [3, 2]LazyIterator.compact
Create LazyIterator without undefined elements.
function compact<I>(this: LazyIterator<I | undefined>): LazyIterator<I>;- Returns
LazyIteratorthat contains only non-undefined elements.
Example:
const iterator = LazyIterator.from([1, 2, 3, undefined, 4, undefined, 15, undefined]);
const compacted = iterator.compact();
for (const a of compacted) console.log(a);
// 1
// 2
// 3
// 4
// 15LazyIterator.contains
Tests if any element of the LazyIterator matches provided element.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function contains<I>(elem: I): boolean;- Returns
LazyIteratorthat contains only non-undefined elements.
Warning: Be careful, iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function contains<I>(elem: I): boolean;elem: I- element which are testing for existing in theLazyIterator.- Returns
trueifelemis existed inLazyIteratorthen returntrueotherwisefalse
Example:
const iterator = LazyIterator.from([1, 2, 3, 4, 5]);
iterator.contains(2); // true
iterator.contains(7); // falseLazyIterator.unique
Create LazyIterator which contains only unique elements.
Warning: Be careful, iterator should save previous elements for the computation. So it create memory leak with large LazyIterator.
function unique<I>(): LazyIterator<I>;- Returns
LazyIteratorthat contains only unique elements.
const iterator = LazyIterator.from([1, 1, 2, 3, 4, 4, 12, 6, 2, 3, 4, 5]);
const unique = iterator.unique();
for (const a of unique) console.log(a);
// 1
// 2
// 3
// 4
// 12
// 6
// 5LazyIterator.isEmpty
Check LazyIterator for emptiness.
function isEmpty(): boolean;- Returns
trueifLazyIteratordoesn't contain any item otherwisefalse.
const iterator1 = LazyIterator.from([1, 2, 3, 4, 5]);
const iterator2 = LazyIterator.from([]);
iterator1.isEmpty(); // false
iterator2.isEmpty(); // trueLazyIterator.except
Create LazyIterator without element which was contained in provided LazyIterator.
Warning: Be careful, provided as argument iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function except<I>(other: LazyIterator<I>): LazyIterator<I>;other: LazyIterator<I>-LazyIteratorwith element which should be excluded fromthisLazyIterator- Returns
LazyIteratorthat doesn't contain elements fromotherLazyIterator.
const iterator = LazyIterator.from([1, 1, 2, 3, 4, 4, 12, 6, 2, 3, 4, 5]);
const excepted = iterator.except(LazyIterator.from([2, 4, 1]));
for (const a of excepted) console.log(a);
// 3
// 12
// 6
// 3
// 5LazyIterator.intersect
Create LazyIterator only with elements which was existed in both LazyIterators.
Warning: Be careful, provided as argument iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function except<I>(other: LazyIterator<I>): LazyIterator<I>;other: LazyIterator<I>-LazyIteratorwith element which should be existed inthisLazyIterator- Returns
LazyIteratorthat contains elements from bothotherandthisLazyIterator.
const iterator = LazyIterator.from([1, 1, 2, 3, 4, 4, 12, 6, 2, 3, 4, 5]);
const intersection = iterator.intersect(LazyIterator.from([2, 4, 1, 8, 15]));
for (const a of intesection) console.log(a);
// 1
// 1
// 2
// 4
// 4
// 2
// 4LazyIterator.isEmpty
Check LazyIterator for emptiness.
function isEmpty(): boolean;- Returns
trueifLazyIteratordoesn't contain any item otherwisefalse.
const iterator1 = LazyIterator.from([1, 2, 3, 4, 5]);
const iterator2 = LazyIterator.from([]);
iterator1.isEmpty(); // false
iterator2.isEmpty(); // trueLazyIterator.except
Convert LazyIterator without element which was contained in provided LazyIterator.
Warning: Be careful, provided as argument iterator should be iterated for the computation. So it doesn't work with infinity iterable objects.
function except<I>(other: LazyIterator<I>): LazyIterator<I>;- Returns
Iterableobject which contains allLazyIteratorelements.
const iterator1 = LazyIterator.from([1, 2, 3, 4, 5], function* (lazy) {
for (const i of lazy) yield i;
});
const iterator2 = LazyIterator.from([1, 2, 3, 4, 5]);
iterator1.collect(); // iterable object
iterator2.collect(); // array [1, 2, 3, 4, 5]LazyIterator.prepend
Create LazyIterator with new element at the head position.
function prepend<I>(item: I): LazyIterator<I>;item: I- element which should be added at the head position ofLazyIterator- Returns
LazyIteratorwhich containsitemat the head position.
const iterator1 = LazyIterator.from([1, 2, 3, 4, 5]);
const iterator2 = iterator1.prepend(4);
for (const a of iterator2) console.log(a);
// 4
// 1
// 2
// 3
// 4
// 5LazyIterator.append
Create LazyIterator with new element in the end.
function append<I>(item: I): LazyIterator<I>;item: I- element which should be added at the end position ofLazyIterator- Returns
LazyIteratorwhich containsitemat the end position.
const iterator1 = LazyIterator.from([1, 2, 3, 4, 5]);
const iterator2 = iterator1.append(4);
for (const a of iterator2) console.log(a);
// 1
// 2
// 3
// 4
// 5
// 4LazyIterator.collect
Convert LazyIterator in initial iterable object or array.
If initial iterable object had fromIterator method or fromIterator was provided as second argument of LazyIterator.from function fromIterator will be called for converting, otherwise convert LazyIterator in array.
function collect<I>(): Iterable<I>;- Returns
Iterableobject which contains allLazyIteratorelements.
const iterator1 = LazyIterator.from([1, 2, 3, 4, 5], function* (lazy) {
for (const i of lazy) yield i;
});
const iterator2 = LazyIterator.from([1, 2, 3, 4, 5]);
iterator1.collect(); // iterable object
iterator2.collect(); // array [1, 2, 3, 4, 5]License
MIT (c) Artem Kobzar see LICENSE file.
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago