This implements the factory methods as defined by IStreamFactory.
Creates instances of TypesafeStream. A typesafe stream creates new instances when chaining methods on the stream. This makes it safe to use with typescript. When an old stream instance is accessed again after chaining, an error can be thrown to indicate this fact.
const stream1 = require("elbe").TypesafeStreamFactory.stream("foo");
// Returns an instance of IStream<string>
const stream2 = stream1.map(x => x.charCodeAt(0));
// Returns an instance of IStream<number>
// Now stream1 and stream2 are of different type and do not
// refer to the same object. The call to #map created a new
// stream instance.
stream1 === stream2 // => false
// Throws an error because stream1 because the mapping operation
// already consumed the stream.
stream1.toArray();
A shortcut for InplaceStreamFactory.
const { factory } = require("elbe")
factory.stream([1,2,3]) // => Stream[1, 2, 3]
factory.times(5) // => Stream[0, 1, 2, 3, 4]
A shortcut for InplaceStreamFactory#stream. Use this to create streams quickly.
const stream = require("elbe").stream("foobar")
stream.size() // => 6
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Overload with tuple types for chunk(chunkSize: number): Iterable<T[]>
Chunks the items into chunks of chunkSize. This is equivalent
to chunkBy(iterable, (_, i) => Math.floor(i/chunkSize))
.
chunk([1,2,3,4,5], 2) // => Iterable[ [1,2], [3,4], [5] ]
chunk([1,2,3,4,5], 1) // => Iterable[ [1], [2], [3], [4], [5] ]
chunk([1,2,3,4,5], 0) // => Iterable[]
chunk([1,2,3,4,5], -1) // => Iterable[]
chunk([1,2,3,4,5], NaN) // => Iterable[]
chunk([1,2,3,4,5], Infinity) // => Iterable[[1,2,3,4,5]]
Type of the elements in the given iterable.
The iterable to be chunked.
Size of the produced chunks.
An iterable over the chunked items.
Chunks together consecutive items for which the classifier
returns the same value. Equality is checked with ===
.
chunkBy([1,2,3,4,5,6,1,2], i => Math.floor((i-1) / 3)) // => Stream[ [1,2,3], [4,5,6], [1,2] ]
Type of the elements in the given iterable.
Type of the returned value of the chunker,
The iterable to be chunked.
It is passed the item as its first argument and the index as its second. Items are chunked together according to the returned value.
An iterable over the chunked items.
Creates and object an incorporates all items into that object.
collect([1,2,3], Collectors.summarize) // => Statistic[min:1, max:3, count: 3, sum: 6, average: 2, variance: 0.67]
Type of the elements in the given iterable.
Type of the intermediate value that incorporates each item in order.
Type of the final collected value.
The iterable to be collected.
How to collect the items.
The collected value.
Same as collect, but allows specifying the parts of the collector individually.
collect([1,2,3], () => [], (array, x) => array.push(x), x => new Set(x))
// => Set[1,2,3]
Type of the elements in the given iterable.
Type of the intermediate value that incorporates each item in order.
Type of the final collected value.
The iterable to be collected.
Takes the intermediate objects as its first argument and the current items as its seconds, and incorporates the item into the intermediate value.
Takes the intermediate object with all the items incoporated, and transforms it into the final value.
The final collected value.
Concatenates all iterables into one iterable of all the items.
concat("foo", "bar", "baz") // => Iterable["f", "o", "o", "b", "a", "r", "b", "a", "z"]
Type of the elements in the given iterable.
An iterable over all the items of the given iterables.
Consumes the given amount of items from the iterable, adding it to the sink, and returns an iterable over the remaining items.
const sink = [];
consume("foobar", sink, 0, 3);
// => sink is now ["f", "o", "o"]
consume("foobar", console.log, 0, 3);
// => logs "f", "o", "o"
consume("foobar", console.log, 0, -3);
// => logs nothing
Type of the elements in the given iterable.
The iterable to be scanned.
If an array, consmed items are added to the array. Otherwise, the consumer is called with the consumed item.
Where to start removing items from the iterable. Defaults to 0
.
Maximum number of items to consume. Defaults to Infinity
.
An iterable over the remaining items.
Cycles over the elements of the iterable the given number of times.
cycle([1,2,3], NaN) // => Iterable[]
cycle([1,2,3], 3) // => Iterable[1,2,3,1,2,3,1,2,3]
limit(cycle([1,2,3]), 5) // => Iterable[1,2,3,1,2]
Type of the elements in the given iterable.
The iterable to be cycled.
The number of cycle. If not given, cycles an unlimited amount of times.
An iterable with the items of the given iterable repeating.
Applies all pending operations, ending the given iterable.
visit([1,2,3], console.log) // Iterable[1,2,3]; prints nothing
end(visit([1,2,3], console.log)) // prints 1,2,3
Type of the elements in the given iterable.
The iterable to be terminated.
Determines whether every items matches the given predicate.
every("fooz", x => x < "j") // => false
Type of the elements in the given iterable.
The iterable to be scanned.
Test to be performed on the items.
Whether every items matches the given predicate.
Removes all elements from the iterable for which the
predicate does not return true
.
filter([4,-4,2,-9], x => x > 0) // => Iterable[4,2]
Type of the elements in the given iterable.
The iterable to be filtered.
Testing function returning true
iff the item is to be kept, false
otherwise.
An iterable over all item for which the predicate returned true
.
Similar to {@link Methods}#filter, but filters out all items not equivalent to the given target. Items are compared to the target by first extracting a key with the given key extractor, and then comparing the keys with the given comparator.
filterBy(["foo", "bar", "foobar"], x => x.length)
// => Iterable["foo", "bar"]
const user1 = {name: "Dave", birth: {day: 5, month: 4, year: 2005}}
const user2 = {name: "Maria", birth: {day: 9, month: 11, year: 2005}}
const user3 = {name: "Odo", birth: {day: 22, month: 7, year: 2004}}
filterBy([user1, user2, user3], 2005, user => user.birth, (lhs,rhs) => lhs.year - rhs.year)
// => Iterable[user1, user2]
Type of the elements in the given iterable.
The iterable to be counted.
Target for filterting. All items in the iterable not equivalent to the target are removed.
Extracts the key by which equality is determined. Default to identity x => x
.
Comparator for comparing two keys. Defaults to the natural comparator using <
and >
.
An iterable with the items not matching the target removed.
Searches for the first occurence of an item matching the predicate.
find(["foo1", "bar,"foo2"], x => x.startsWith("foo")) // => "foo1"
Type of the elements in the given iterable.
The iterable to be scanned.
Test to be performed on the items. It is passed the current item and the current index.
The item iff found, undefined otherwise.
Searches for the first occurence of an item matching the predicate,
and returns the index; or -1
otherwise.
findIndex(["foo1", "bar, "foo2"], x => x.startsWith("foo")) // => 0
Type of the elements in the given iterable.
The iterable to be scanned.
Test to be performed on the items. It is passed the current item and the current index.
The index iff the item was found, -1
otherwise.
Returns the first item.
first("foo") // => "f"
first("") // => undefined
Type of the elements in the given iterable.
The iterable to be scanned.
The item at the first position, or undefined if empty.
Applies the mapping function to each item and return an iterable
over all the mapped iterables.
This is equivalent to concat(map(mapper))
.
flatMap(["foo","bar"], x => fromString(x)) // => Iterable["f", "o", "o", "b", "a", "r"]
flatMap(doTry(["[1]","[2,3]","[4,]"], JSON.parse), x=>x.iterate()) // => Iterable[ [1], [2, 3] ]
Type of the elements in the given iterable.
Type of the elements in the produced iterable.
The iterable to be flat-mapped.
Mapping function taking each item and producing a new iterable.
An iterable over all the items of the iterables produced by the mapper.
This returns an iterable that can be iterated over any number of times. If the iterable is an array, set, map or string etc, it simpy return the iterable, otherwise it stores the items temporarily.
function * foo() {
return 1;
return 2;
return 3;
}
const transientIterable = foo();
Array.from(transientIterable) // => [1,2,3]
Array.from(transientIterable) // => []
const persistentIterable = fork(foo());
Array.from(persistentIterable) // => [1,2,3]
Array.from(persistentIterable) // => [1,2,3]
Note that buffering takes place on-demand, so the following will not enter an infinite loop:
// Create an iterable with an unlimited amount of items.
const iterable = generate(Math.random, Infinity);
// Fork the iterable first, then limit to a finite number of items.
// Items already produced are not recomputed.
Array.from(limit(fork(iterable), 3)) // => [0.28, 0.14, 0.97]
Array.from(limit(fork(iterable), 2)) // => [0.28, 0.14]
Array.from(limit(fork(iterable), 4)) // => [0.28, 0.14, 0.97, 0.31]
Type of the elements in the given iterable.
The iterable to to be persisted.
A persistent iterable.
Creates an iterable from the given iterable or iterator. If it is an iterable, returns that iterable, otherwise create an iterabl reading from the iterator.
fromIter([1,2,3]) // => Iterable[1,2,3]
const set = new Set([1,2,3])
fromIter(set.values().next()) // => Iterable[2,3]
Type of the generated items.
Iterable or iterator from which to read the items.
An iterable over the iterable's or the iterator's items.
Creates an iterable for iterating over an object's key-value-pairs. Only the object's own property are included.
fromObject({foo:2, bar: 3})
// => Iterable[ {key: "foo", value: 2}, {key: "bar", value: 3} ]
Type of the object's values.
The object with the key-value-pairs to be iterated.
An iterable with the object's key-value-pairs.
Creates an iterable for iterating over an object's keys. Only the object's own property are included.
fromObjectKeys({foo:2, bar: 3, 42: 9})
// => Iterable["foo", "bar", "42"]
The object with the keys to be iterated.
An iterable with the object's keys.
Creates an iterable for iterating over an object's values. Only the object's own property are included.
fromObjectValues({foo:2, bar: 3})
// => Iterable[2,3]
Type of the object's values.
The object with the values to be iterated.
An iterable with the object's values.
Creates an iterable with the items provided by the given generator.
generate(index => index, 2) // => Iterable[0,1,2]
generate(index => index, 0) // => Iterable[]
generate(index => index) // => Iterable[0,1,2,3,4,...]
generate(index => index, Infinity) // => Iterable[0,1,2,3,4,...]
generate(index => index, -Infinity) // => Iterable[]
generate(index => index, NaN) // => Iterable[]
Type of the generated items.
Generator for generating the items of the iterable. It is passed the current index as its argument.
How many items to generate, Infinity
for an unlimited amount.
Iterable for iterating the given amount of times over the items supplied by the supplier.
Splits the items into several groups, according to the given classifier.
group(["a", "foo", "is", "some", "buzz"], x => x.length)
// => Map [ 1 => ["a"], 2 => ["is"], 3 => "is", 4 => ["some", "buzz"] ]
Type of the elements in the given iterable.
The iterable to be grouped.
Returns the group for each item.
A map with the groups as keys and arrays as values, containg all the items for that group.
Determines whether the iterable contains the given item.
Equivalence is checked with ===
. This is
equivalent to some(iterable, x => x === object)
.
has("foobar", "o") // => true
Type of the elements in the given iterable.
The iterable to be scanned.
Whether the given object is contained in the iterable.
Adds the index to each element of the given iterable. The index starts at 0
index(["foo", "bar"]) // => Iterable<[ {index: 0, value: "foo"}, {index: 1, value: "bar"} ]>
Type of the element in the iterable.
The iterable to be indexed.
An iterable with each item being an object containing the item's index and the item itself. The index starts at 0.
Determines whether the iterable contains no items. This consumes at most one item from the iterable and works with infinite iterables.
isEmpty([]).result // => true
isEmpty([1,2,3]).result // => false
Type of the elements in the given iterable.
True iff the iterable contains no items or false otherwise; and an iterable over the original items.
Determines whether the number of items in the iterable is at least lower
and at most upper
.
This method only consumes as many elements from the iterable as necessary and may be used with
infinite iterables. Using size(iterable) === 0
would force an endless iteration of all its item.
isSizeBetween[1,2,3]).result // => true
isSizeBetween[1,2,3], 1, 3).result // => true
isSizeBetween[1,2,3], 3, 3).result // => true
isSizeBetween[1,2,3], 3, 4).result // => true
isSizeBetween[1,2,3], -4, 2).result // => false
isSizeBetween[1,2,3], 4, 9).result // => false
isSizeBetween[1,2,3], 1, 2).result // => false
isSizeBetween[1,2,3], 2, Infinity).result // => true
isSizeBetween[1,2,3], 0).result // => true
isSizeBetween[1,2,3], 1).result // => true
isSizeBetween[1,2,3], 3).result // => true
isSizeBetween[1,2,3], 4).result // => false
isSizeBetween[], 0, 0).result // => true
isSizeBetween[], 1, 3).result // => false
isSizeBetween[]).result // => true
isSizeBetween[1,2,3]).result // => true
isSizeBetween[], NaN).result // => false
isSizeBetween[1,2,3], NaN).result // => false
isSizeBetween[], NaN, NaN).result // => false
isSizeBetween[1,2,3], NaN, NaN).result // => false
Type of the elements in the given iterable.
The iterable to be counted.
Minimum number of items allowed. Defaults to 0
.
Maximum number of items allowed. Defaults to Infinity
.
True iff the iterable contains the specified number of items or false otherwise; and an iterable over the original items.
Creates an iterable starting with the initial seed.
iterate(42, x => (0x19660D * x + 0x3C6EF35F) % 0x100000000)
// Random number generator, linear congruential generator from "Numerical Recipes".
iterate(2, x => 2*x, 3) // => Iterable[2,4,8]
iterate(2, x => 2*x, 0) // => Iterable[]
iterate(2, x => 2*x, Infinity) // => Iterable[2,4,8,16,...]
iterate(2, x => 2*x, -Infinity) // => Iterable[]
iterate(2, x => 2*x, NaN) // => Iterable[]
Type of the items of the produced iterable.
Initial item.
Function that takes the current item and produces the next item in the sequence.
How many times to iterate, Infinity
for an unlimited amount.
Iterable for iterating over the provided items the given amount of times.
Joins every time with the given delimiter, optionally prepending a prefix and appending a suffix to the output.
join([1,2,3], ",", "[", "]") // => "[1,2,3]"
Type of the elements in the given iterable.
The iterable to be joined.
String inserted between the items.
String prepended to the joined string.
String appended to the joined string.
A string consisting of the prefix, the items joined with the delimiter, and the suffix.
Returns the last item.
last("foo") // => "o"
last("") // => undefined
Type of the elements in the given iterable.
The iterable to be scanned.
The item at the last position, or undefined if empty.
Limits the iterable to at most the given number of elements.
limit([1,2,3,4,5,6], NaN) // => Iterable[1,2,3,4,5,6]
limit([1,2,3,4,5,6], 0) // => Iterable[]
limit([1,2,3,4,5,6], 3) // => Iterable[1,2,3]
Type of the elements in the given iterable.
The iterable to be limited.
The maximum number of items in the resulting iterable. Default to Infinity
.
An iterable with at most the given number of items.
Transform each element to another element of a different type.
map([0,1,2,3], x => 2 * x) // => Iterable[0,2,4,6]
Type of the elements in the given iterable.
Type of the elements in the produced iterable.
The iterable to be mapped.
A function taking each item of the given iterable and transforms it into another item.
An iterable over the mapped elements.
Computes the maxmimum of the items.
max([3,2,9,4]) // => 9
max(["foo", "bar", "I"], Comparators.byField("length")) // => "foo"
max([]) // => undefined
Type of the elements in the given iterable.
The iterable to be maximized.
How two items are compared. Defaults to the natural order, ie. by using <
and >
.
The largest item. If there are multiple largest items, returns the first. undefined
iff the iterable is empty.
Computes the minimum of the items, as determined by the given sort key.
maxBy(["foo","foobar", "gg"], x => x.length)
// => "foobar"
Type of the elements in the given iterable.
The iterable to be maximized.
Takes an item and produces the key by which the maximum is determined.
The smallest item, or undefined
iff there are no items.
Computes the minimum of the items.
min([3,2,9,4]) // => 9
min(["foo", "bar", "I"], Comparators.byField("length")) // => "I"
min([]) // => undefined
Type of the elements in the given iterable.
The iterable to be minimized.
How two items are compared. Defaults to the natural order, ie. by using <
and >
.
The smallest item. If there are multiple smallest items, returns the first. undefined
iff the iterable is empty.
Computes the minimum of the items, as determined by the given sort key.
minBy(["foo","foobar", "gg"], x => x.length)
// => "gg"
Type of the elements in the given iterable.
The iterable to be minimized.
Takes an item and produces the key by which the minimum is determined.
The smallest item, or undefined
iff there are no items.
Patches a few stream convenience methods to the prototype of objects:
Stream<string>
Creates a stream over all characters.Stream<T>
Creates a stream over all items.Stream<T>
Creates a stream over all items.Stream<K,V>
Creates a stream over all key-value pairs.Stream<{key: string, value: T}>
Creates a stream over all key-value pairs.Stream<string>
Creates a stream over all keys.Stream<T>
Creates a stream over all values.require("elbe").monkeyPatch();
"foo".stream() // => Stream["f", "o", "o"]
[1,2,3].stream() // => Stream[1, 2, 3]
{foo: 42, bar: 99}.keys() // => Stream["foo", "bar"]
Iff true
, uses InplaceStreamFactory or TypesafeStreamFactory otherwise.
Iff true
, always add the methods to the prototype. Otherwise, does nothing if the methods exist already.
Determines whether no item matches the given predicate. This
is equivalent to !some(iterable, predicate)
.
none("fooz", "x => x < "j") // => false
Type of the elements in the given iterable.
The iterable to be scanned.
Test to be performed on each item.
Whether no item matches the given predicate.
Returns the item at the n-th position.
nth("foo", -1) // => "f"
nth("foo", 0) // => "f"
nth("foo", 2) // => "o"
nth("foo", 3) // => undefined
Type of the elements in the given iterable.
The iterable to be scanned.
The position of the item to get.
The item at the given position, or undefined if not found.
Splits the items into two groups according to the given discriminator.
partition([-3,2,9,-4], x => x > 0)
// => { false: [-3,-4], true: [2,9]}
partition([], x => x > 0)
// => { false: [], true: []}
Type of the elements in the given iterable.
The iterable to be partitioned.
Partitions each item into one of two groups by returning true
of false
.
An object containing the partitioned items.
Converts each item to a promise and returns a promise that is resolved with an iterable of results when all of the created Promises resolve, or rejected when any Promise is rejected.
promise([1,2,3], id => fetch(`/user/${id}`))
.then(s => s.forEach(renderUser))
.catch(console.error)
// Calls the renderUser method with the Response for each user request.
Type of the elements in the given iterable.
Type of the item of the promises.
The iterable to be scanned.
Takes each item and creates a promise.
A promise that resolves when all promises resolve; or is rejected when any promise is rejected.
Creates an iterable of random numbers. The generated numbers are
in the interval [0,1]
. When the amount of numbers to generate
is not specified, an unlimited amount of numbers are generated.
Use methods such as {@link Methods.limit} to limit the iterable or
{@link Methods.consume} to extract only a few numbers.
Please note that the generated numbers are not cryptographically secure random numbers and must not be used in any context dealing with security.
random(3) // => Iterable[3 random numbers]
random(-1) // => Iterable[]
limit(random(Infinity), 5) // => Iterable[5 random numbers]
first(random(10)) // => 1 random number
How many random numbers to generate. Defaults to Infinity
.
A stream with the specified amount of random numbers.
Coalesces all items into one value.
reduce([1,2,3], (sum,x) => sum + x, 10) // => 16
Type of the elements in the given iterable.
Type of the reduced value.
The iterable to be reduced.
Takes the current reduced value as its first argument and the current item as its second, combines the item with the current reduced value, and returns that value.
The initial value of the reduction.
The reduced value, or the initial value iff the iterable is empty.
Similar to reduce, but reduces to items of the same type as the items and thus does not require an initial value.
reduceSame([1,2,3], (sum,x) => sum + x) // => 6
Type of the elements in the given iterable.
The iterable to be reduced.
Takes the current reduced value as its first argument and the current item as its second, combines the item with the current reduced value, and returns that value.
The reduced value, or undefined iff the iterable is empty.
Creates an iterable with the given item occuring the given number of times.
repeat(0, 9)
// => Iterable[0,0,0,0,0,0,0,0,0]
repeat(0, 0) // => Iterable[]
repeat(0, -Infinity) // => Iterable[]
repeat(0, Infinity) // => Iterable[0,0,0,...]
repeat(0, NaN) // => Iterable[]
Type of the items of the produced iterable.
Item to repeat.
How many times to repeat, Infinity
for an unlimited amount.
Iterable contains the given item the given number of times.
Reverses the order of the items.
Note that the items need to be saved temporarily, so that this does not work with unlimite streams, as the last item needs to be accesed first.
This method might create a new array, but if it does, calling toArray
with
the returned iterable will return that array instead of allocating a new array.
reverse([1,2,3]) // => Iterable[3,2,1]
reverse([]) // => Iterable[]
reverse(factory.step(Infinity)) // hangs
Type of the elements in the given iterable.
The iterable to be reversed.
An iterable with the items in reversed order.
Counts the items.
count([1,2,3]) // => 3
The iterable to be counted.
The number of items in the iterable.
Discards the given number of items from the iterable.
skip([1,2,3,4,5,6], Infinity) // => Iterable[]
skip([1,2,3,4,5,6], NaN) // => Iterable[1,2,3,4,5,6]
skip([1,2,3,4,5,6], 0) // => Iterable[1,2,3,4,5,6]
skip([1,2,3,4,5,6], 3) // => Iterable[4,5,6]
Type of the elements in the given iterable.
The iterable to be skipped.
Number of items to skip. Default to Infinity
.
An iterable with the given number of items skipped.
Returns the items from the startOffset
up to, but not including, the endOffset
.
The returned iterable is left unchanged, all items are still available for further
consumption.
const iterable = slice("foobar", 0, 3);
// => ["f", "o", "o"]
join(iterable) // => "foobar"
const iterabl2 = slice("foobar", 2, 5);
// => ["o", "b", "a"]
join(s) // => "forbar"
// special cases
slice("foo", 0, 0) // => []
slice("foo", 3, 2) // => []
slice("foo", 0, 2.5) // => ["f", "o"]
slice("foo", 0.5, 2) // => ["f", "o"]
slice("foo", -5, 2) // => ["f", "o"]
slice("foo", 0, Infinity) // => ["f", "o", "o"]
slice("foo", Infinity, 9) // => []
slice("foo", 0, NaN) // => []
slice("foo", NaN, 2) // => []
slice("foo", NaN, NaN) // => []
slice(generate(Math.random), Infinity, Infinity) // => []
Type of the elements in the given iterable.
The iterable to be counted.
Position (inclusive) at which to start removing items from the iterable. Default to 0
.
Position (not inclusive) at which to stop removing items from the iterable. Defaults to Infinity
.
The items in the iterable from startOffset
up to, but not including, endOffset
.
Determines whether at least one items matches the given predicate.
some("fooz", x => x < "j") // => true
Type of the elements in the given iterable.
The iterable to be scanned.
Test to be performed on the items.
Whether some (at least one) item matches the given predicate.
Sorts the items. Consider converting the iterable to an array and sorting this array if you do not need an iterable for further operations.
This method might create a new array, but if it does, calling toArray
with
the returned iterable will return that array instead of allocating a new array.
sort(["foobar", "a", "bar", Comparators.byField("length")] // => Iterable["a", "bar", "foobar"]
Type of the elements in the given iterable.
The iterable with to be sorted.
How to sort the items. Default to the natural order.
An iterable with the items in sorted order.
Similar to {@link Methods}#sort, but sorts items by comparing them according to the given key extractor and comparator. For each item, a key is extracted, two items are then compared by comparing theirs keys with the given comparator.
This method might create a new array, but if it does, calling toArray
with
the returned iterable will return that array instead of allocating a new array.
sortBy(["foo", "foobar", "bar"], x => x.length)
// => Iterable["foo", "bar", "foobar"]
const user1 = {name: "Dave", birth: {day: 5, month: 4, year: 1990}}
const user2 = {name: "Maria", birth: {day: 9, month: 11, year: 2005}}
const user3 = {name: "Odo", birth: {day: 22, month: 7, year: 2004}}
sortBy([user1, user2, user3], user => user.birth, (lhs,rhs) => lhs.year - rhs.year)
// => Iterable[user1, user3, user1]
Type of the elements in the given iterable.
The iterable to be counted.
Extracts the key by which the sort order is determined. Default to identity x => x
.
Comparator for comparing two keys. Defaults to the natural comparator using <
and >
.
An iterable with the items in sorted order.
Extracts and return at most maxAmount
items from the iterable, starting
at the given start position. All items up to the starting point and the
remaining items are left in the returned iterable and can still be iterated over.
const result = splice("foobar", 0, 3);
// => {iterable: {}, result: ["f", "o", "o"]}
join(result.iterable) // => "bar"
const result2 = splice("foobar", 2,3);
// => {iterable: {}, result: ["o", "b", "a"]}
join(result2.iterable) // => "for"
// special cases
splice("foo", 0, 0).result // => []
splice("foo", 0, Infinity).result // => ["f", "o", "o"]
splice("foo", Infinity, 9).result // => []
splice("foo", 0, NaN).result // => []
splice("foo", NaN, 2).result // => []
splice("foo", NaN, NaN) // => []
splice(generate(Math.random), Infinity, 0) // => []
Type of the elements in the given iterable.
The iterable to be counted.
Position at which to start removing items from the stream. Default to 0
.
Maximum number if items to read from this stream. Defaults to Infinity
.
At most maxAmount
items from the given start position of this stream.
Creates an iterable with numbers starting at the given value and separated from each other by the given step.
step(3) // => Iterable(0,1,2)
step(3, 4) // => Iterable(4, 5, 6)
step(3, 4, 8) // => Iterable(4, 12, 20)
step(-3) // => Iterable()
step(3, -4) // => Iterable(-4, -3, -2)
step(3, 4, -2) // => Iterable(4, 2, 0)
step(3, -4, -2) // => Iterable(-4, -6, -8)
step(Infinity) // => Iterable(0, 1, 2, 3, ...)
step(-Infinity) // => Iterable()
step(Infinity, 5) // => Iterable(5, 6, 7, 8, ...)
step(Infinity, 5, 2) // => Iterable(5, 7, 9, 11, ...)
step(3, Infinity) // => Iterable(Infinity, Infinity, Infinity)
step(4, 0, Infinity) // => Iterable(0, Infinity, Infinity, Infinity)
step(4, Infinity, Infinity) // => Iterable(Infinity, Infinity, Infinity, Infinity)
step(4, -Infinity, Infinity) // => Iterable(-Infinity, NaN, NaN, NaN)
step(Infinity, 2, Infinity) // => Iterable(2, Infinity, Infinity, Infinity, ...)
step(Infinity, Infinity, 2) // => Iterable(Infinity, Infinity, Infinity, Infinity, ...)
step(Infinity, -Infinity, 2) // => Iterable(-Infinity, -Infinity, -Infinity, -Infinity, ...)
step(Infinity, Infinity, Infinity) // => Iterable(Infinity, Infinity, Infinity, Infinity, ...)
step(NaN) // => Iterable()
step(5, NaN) // => Iterable(NaN, NaN, NaN, NaN, NaN)
step(5, 1, NaN) // => Iterable(1, NaN, NaN, NaN, NaN)
step(5, Infinity, NaN) // => Iterable(Infinity, NaN, NaN, NaN, NaN)
step(5, -Infinity, NaN) // => Iterable(-Infinity, NaN, NaN, NaN, NaN)
step(5, NaN, 2) // => Iterable(NaN, NaN, NaN, NaN, NaN)
step(5, NaN, NaN) // => Iterable(NaN, NaN, NaN, NaN, NaN)
step(NaN, NaN, NaN) // => Iterable()
Number of items to produce. Must not be negative.
Initial number, defaults to 0.
How far apart the individual items are, defaults to 1.
Iterable with the configured numbers.
Sums all items arithmetically.
sum([1,2,3]) // => 6
sum(["I", "of", "Borg"], x => x.length) // => 7
Type of the elements in the given iterable.
The iterable to be summed.
The sum of the items.
Creates an iterable with numbers starting at the given value and ending at the given value.
times(3) // => Iterable(0,1,2)
times(3, 4) // => Iterable(4,5,6)
times(3, 4, 8) // => Iterable(4,6,8)
times(1, 10, 12) // => Iterable(10)
times(0) // => Iterable()
times(3, 0, -2) // => Iterable(0, -1, -2)
times(-3) // => Iterable()
times(5, 0, Infinity) // => Iterable(0, NaN, NaN, NaN, Infinity)
times(5, Infinity, 0) // => Iterable(Infinity, NaN, NaN, NaN, 0)
times(Infinity) // => Iterable(0, 0, 0, 0, ...)
times(Infinity, 2, 3) // => Iterable(2, 2, 2, 2, ...)
times(NaN) // => Iterable()
times(5, NaN) // => Iterable(NaN, NaN, NaN, NaN, NaN)
times(5, 2, NaN) // => Iterable(2, NaN, NaN, NaN, NaN)
times(5, NaN, 7) // => Iterable(NaN, NaN, NaN, NaN, 7)
times(NaN, 0, 5) // => Iterable()
times(NaN, NaN, NaN) // => Iterable()
Number of items to produce. Must not be negative.
Initial number, defaults to 0.
Last number, defaults to start+amount-1
. May be smaller than end, in which case numbers of decreasing value are generated.
Iterable with the configured numbers.
Creates an array with the items of the given iterable. If the underlying iterable is an array, returns that array instead of creating a new array.
toArray("foobar")
// => ["f", "o", "o", "b", "a", "r"]
Type of the elements in the given iterable.
The iterable to to be converted.
Iff true, always creates a new array. Otherise, reuses existing array when possible.
An array with the items.
Creates a map from the items of the given iterable. The item's key and value is extracted by the given key and value mapper.
When two items have the same key, the optional merge function is called with the two items and the result of the merge function is used as the value for that key. If no merge function is given, the value of the item encountered first is taken.
toMap(["foo", "bar"], x => x, x => x.length)
// => Map[ "foo" => 3, "bar" => 3 ]
Type of the elements in the given iterable.
Type of the map's keys.
Type of the map's values.
The iterable to to be converted.
Transforms an item into the map key to be used.
Transforms an item into the value used for the corresponding key.
A merge function called when two items map to the same key and returns the merged value. Called with two items having the same key, the first argument is the item encountered first in the stream.
A map with all the mapped key-value-pairs of the items.
Creates a set with the items of the given iterable. If the underlying iterable is a set, returns that set instead of creating a new set.
toSet("foobar")
// => Set["f", "o", "b", "a", "r"]
Type of the elements in the given iterable.
The iterable to to be converted.
Iff true, always creates a new set. Otherise, reuses existing set when possible.
A set with the items.
Passes the given iterable to the the operation and returns its result, wrapped in a {@link Try} in case the operation throws an error. Usually used for performing a terminal operation with error handling on the iterable.
tryCompute([1,2,3], it => reduce(it, item => {throw new Error()}, 0))
// => Try[success=false]
Type of the elements in the given iterable.
Type of the value produced by the operation.
The iterable to to be processed.
Takes the given iterable and returns a value. If it throws an error, the resulting {@link Try} is not successful.
The result of the operation, wrapped in a {@link Try} for encapsulating thrown errors.
Same as {@link end}, but encapsulates any errors thrown. Applies all pending operation to the pipeline.
tryEnd(visit([1,2,3], console.log)) // prints 1,2,3
Type of the elements in the given iterable.
The iterable to to be processed.
The encapsulated error, if any was thrown.
Similar to map, but handles any error that may be thrown by
the mapper by wrapping them in a {@link Try}. This is equivalen to
map(x => Try.of(() => mapper(x)))
doTry(["[1]","[2,3]","[4,]"], JSON.parse)
// => Iterable[ Try[1], Try[2,3], Try[ParseError] ]
Type of the elements in the given iterable.
Type of the elements wrapped in a {@link Try} in the produced iterable.
The iterable to to be processed.
Mapping function that takes an item of the given iterable and produces a mapped item. If it throws an error, the resulting {@link Try} is not successful.
An iterable over the mapped elements, wrapped in a {@link Try} for encapsulating thrown errors.
Filters all elements that are considered equal according to the given comparator. If two items are equal, the first one is included in the resulting iterable. Consider using uniqueBy if possible for better performance.
unique([4,1,3,4,1,3,1,9])
// => Iterable[4,1,3,9]
unique({id:4},{id:2},{id:4]}, (x,y) => x.id - y.id)
// => Iterable[ {id:4}, {id:2} ]
Type of the elements in the given iterable.
The iterable to be made unique
Takes two items and returns 0 if they are equal. Defaults to taking determining equality by ===
.
An iterable with all duplicates removed.
Similar to unique, but allows for a custom key to be specified, according to which uniqueness is determined.
distinct([4,1,3,4,1,3,1,9])
// => Iterable[4,1,3,9]
distinct({id:4},{id:2},{id:4]}, customer => customer.id)
// => Iterable[ {id:4}, {id:2} ]
Type of the elements in the given iterable.
The iterable to be made unique
Returns a key for each item. Items with duplicate keys are removed. Defaults to taking the item itself as the key.
An iterable with all duplicates removed.
Calls the given consumer once for each item. The consumer is not called before the stream is consumed by some terminal operation.
visit([1,2,3], console.log)
// => Iterable[1,2,3]
// prints `1,2,3` once the stream is consumed.
Type of the elements in the given iterable.
The iterable to be limited.
Callback taking each item.
An iterable with the same items as the given iterable.
Produces an iterable over pairs of consisting of an item of the given iterable and
the corresponding item of the other iterable.
If one of the given iterable is longer, the shorter one is appended with undefined
.
zip(["foo", "bar"], [3, 4])
// => Iterable[ ["foo",3], ["bar", 4] ]
zip(["foo", "bar"], [3])
// => Iterable[ ["foo",3], ["bar", undefined] ]
toMap(zip(["foo", "bar"], [3, 4]), x=>x[0], x=>x[1])
// => Map[ "foo" => 3, "bar" => 4] ]
Type of the elements in the given iterable.
The iterable to be zipped with the other.
Other iterable to be zipped to the given iterable.
An iterable over all the produced pairs.
Produces an iterable over tuples of consisting of an item of the given iterable and
the corresponding items of the other iterables.
If any of the iterables has a different length than the others,
the shorter ones appended with undefined
to the length of the longest.
zipSame("ab", ["cd", "ef"])
// => Iterable[ ["a","c", "d"], ["b", "d", "f"] ]
zipSame("abc", ["d", "ef"])
// => Iterable[ ["a","d", "e"], ["b", undefined, "f"], ["c", undefined, undefined] ]
toArray(zipSame("fb",["oa","or"])).map(x=>x.map(String).join("")).join("")
// => "foobar"
Type of the elements in the given iterable.
The iterables to be zipped with the others.
Other iterable to be zipped to the given iterable.
An iterable over al the produced tuples.
This implements the factory methods as defined by the interface Collectors.
This implements the factory methods as specified by ITryFactory.
Generated using TypeDoc
This implements the factory methods as defined by IStreamFactory.
Creates instances of InplaceStream. An inplace stream does not create instances when chaining methods on the stream, but switches out the underlying iterable is is thus not immutable. This requires casting and it makes it unsafe with typescript. When a stream object is accessed again after chaining, no error can be thrown. The InplaceStream is slightly faster as it does not need to create new instances.
const stream1 = require("elbe").InplaceStreamFactory.stream("foo"); // Returns an instance of IStream<string> const stream2 = stream1.map(x => x.charCodeAt(0)); // Returns an instance of IStream<number> // Now stream1 and stream2 refer to the same object, but are deemed // to be of differing types by the typescript compiler. stream1 === stream2 // => true stream2.toArray(); // => [102, 11, 111] // This should throw an error because stream1 was consumed // when it got mapped, but this is not possible with InplaceStream. stream1.toArray();
IStreamFactory