A stream is an iterable, lazy sequence of elements.

Type Parameters

  • T

    the type of the elements within the stream

Implements

  • Iterable<T>

Methods

  • Generates an infinite stream of integers, starting with start (which defaults to 0). In other words, this produces the interval [start, start + 1, ...). The returned stream is infinite, truncate the stream accordingly by using for example take(), or break in a for...of loop.

    Parameters

    • Optionalstart: number

      the start value

    Returns Stream<number>

    import { Stream } from "apprt-streams/Stream";
    const numbers = Stream.allIntegers().take(3).toArray(); // [0, 1, 2]
  • Creates a new stream by chaining the given iterables after each other.

    Type Parameters

    • Ts extends Iterable[] | [Iterable]

    Parameters

    • ...iterables: Ts

      the iterables to concatenate

    Returns Stream<ConcatValue<Ts>>

    import { Stream } from "apprt-streams/Stream";
    const result = Stream.concat([1], [2]).toArray(); // [1, 2]
  • Creates a new, empty stream.

    Type Parameters

    • U = any

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";
    Stream.empty().count(); // 0
  • Creates a stream that iterates over the [key, value] pairs of the given object.

    Type Parameters

    • K extends string
    • U

    Parameters

    • object: Record<K, U>

    Returns Stream<[key: K, value: U]>

    import { Stream } from "apprt-streams/Stream";
    const input = { a: 1, b: 2};
    const output = Stream.entries(input).map((e) => `${e[0]}${e[1]}`).toArray(); // ["a1", "b2"] (order might differ)
  • Generates [index, value] tuples where value is from the original iterable and index is the index of the current value.

    Type Parameters

    • U

    Parameters

    • iterable: Iterable<U>

    Returns Stream<[index: number, value: U]>

    import { Stream } from "apprt-streams/Stream";

    const result = Stream.enumerate(["a", "b"]).toArray(); // [[0, "a"], [1, "b"]]
  • Wraps an iterable into a stream.

    The returned stream can be iterated multiple times if the original iterable can also be iterated multiple times (some iterables, like generators, do not support repeated iteration).

    Type Parameters

    • U

    Parameters

    • iterable: Iterable<U>

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";
    Stream.from([]); // Wraps any iterable
    Stream.from(Stream.empty()); // Returns original stream for stream arguments
  • Wraps an iterable into a stream.

    The returned stream can be iterated multiple times if the original iterable can also be iterated multiple times (some iterables, like generators, do not support repeated iteration).

    Type Parameters

    • U

    Parameters

    • iterable: undefined | null | Iterable<U>

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";
    Stream.from([]); // Wraps any iterable
    Stream.from(Stream.empty()); // Returns original stream for stream arguments
  • Generates a stream by repeatedly invoking the provided supplier function. The returned stream is infinite, truncate the stream accordingly by using for example take(), or break in a for...of loop.

    Type Parameters

    • U

    Parameters

    • supplier: () => U

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";

    let nextValue = 1;
    function generateNumbers() {
    return nextValue++;
    }

    const items = Stream.generate(generateNumbers).take(4).toArray(); // [1, 2, 3, 4]
  • Generates a stream of count integers, starting with 0. In other words, this produces the interval [0, 1, ..., count).

    Parameters

    • count: number

      the number of integers to produce

    Returns Stream<number>

    import { Stream } from "apprt-streams/Stream";
    const numbers = Stream.integers(3).toArray(); // [0, 1, 2]
  • Generates a stream of count integers, starting with the provided start index. In other words, this produces the interval [start +0, start +1, ..., start +count).

    Parameters

    • start: number

      the start value

    • count: number

      the number of integers to produce

    Returns Stream<number>

    import { Stream } from "apprt-streams/Stream";
    const numbers = Stream.integers(3, 4).toArray(); // [3, 4, 5, 6]
  • Creates a stream that iterates over the keys of the given object.

    Type Parameters

    • K extends string
    • U

    Parameters

    • object: Record<K, U>

    Returns Stream<K>

    import { Stream } from "apprt-streams/Stream";
    const input = { a: 1, b: 2};
    const output = Stream.keys(input).map((k) => k + k).toArray(); // ["aa", "bb"] (order might differ)
  • Creates a stream from the given items.

    Type Parameters

    • U

    Parameters

    • ...items: U[]

    Returns Stream<U>

  • Creates a stream that iterates over the values of the given object.

    Type Parameters

    • K extends string
    • U

    Parameters

    • object: Record<K, U>

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";
    const input = { a: 1, b: 2};
    const output = Stream.values(input).map((v) => v * 2).toArray(); // [2, 4] (order might differ)
  • Creates a new stream by zipping the elements of the given iterables. The iterables will be iterated in parallel, so each element of the new stream will be a tuple with one element per iterable.

    The stream stops when the shortest of the given iterables has ended.

    Type Parameters

    • Ts extends Iterable[] | [Iterable]

    Parameters

    • ...iterables: Ts

      the iterables to concatenate

    Returns Stream<MapIterableValues<Ts>>

    import { Stream } from "apprt-streams/Stream";
    const left = [1, 2];
    const right = ["a", "b", "c"];
    const zipped = Stream.zip(left, right).toArray(); // [[1, "a"], [2, "b"]]
  • Creates a new stream by zipping the elements of the given iterables. The iterables will be iterated in parallel, so each element of the new stream will be a tuple with one element per iterable.

    The stream stops when the longest of the given iterables has ended. When individual iterables are exhausted, their tuple items are set to undefined.

    Type Parameters

    • Ts extends Iterable[] | [Iterable]

    Parameters

    • ...iterables: Ts

      the iterables to zip

    Returns Stream<ZipLongestValue<Ts>>

    import { Stream } from "apprt-streams/Stream";
    const left = [1, 2];
    const right = ["a", "b", "c"];
    const zipped = Stream.zipLongest(left, right).toArray(); // [[1, "a"], [2, "b"], [undefined, "c"]]
  • Allows iteration in for...of loops.

    Returns Iterator<T>

    for (const value of Stream.integers(5)) {
    console.info(value);
    }
  • Returns a stream over the original items grouped into chunks of size chunkSize. Up to chunkSize consecutive elements will be gathered into an array and then returned by the stream.

    All arrays, except for the last one, will be of length chunkSize.

    Parameters

    • chunkSize: number

      the maximum chunk size

    Returns Stream<T[]>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2, 3, 4, 5];
    const chunked = Stream.from(items).chunk(3).toArray(); // [[1, 2, 3], [4, 5]]
  • Chains the given iterables after this (see static concat function for details).

    Type Parameters

    • Ts extends Iterable[] | [Iterable]

    Parameters

    • ...iterables: Ts

      the iterables to concatenate

    Returns Stream<ConcatValue<[Stream<T>, ...Ts[]]>>

  • Returns the number of elements in this stream.

    NOTE: this will iterate over the entire stream!

    Returns number

  • Returns a stream that repeats the elements of this stream. The returned stream is infinite, truncate the stream accordingly by using for example take(), or break in a for...of loop.

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2];
    const cycled = Stream.from(items).cycle().take(5).toArray(); // [1, 2, 1, 2, 1]
  • Generates [index, value] tuples where value is from the original iterable and index is the index of the current value.

    Returns Stream<[index: number, value: T]>

  • Determines if all items in the stream fulfill the given predicate.

    NOTE: Trivially returns true if the stream is empty.

    Parameters

    • predicate: (item: T) => boolean

      Returns true if all item in the stream fulfills the given predicate, false otherwise.

    Returns boolean

  • Returns a stream that filters the input by predicate. Only items for which predicate(item) returns true will be produced by the stream.

    Type Parameters

    • U

    Parameters

    • predicate: (item: T) => item is U

      A function that returns true if the item should be part of the returned stream.

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, -2, 3];
    const result = Stream.from(items).filter(n => n > 0).toArray(); // [1, 3]
  • Returns a stream that filters the input by predicate. Only items for which predicate(item) returns true will be produced by the stream.

    Parameters

    • predicate: (item: T) => boolean

      A function that returns true if the item should be part of the returned stream.

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, -2, 3];
    const result = Stream.from(items).filter(n => n > 0).toArray(); // [1, 3]
  • Returns a stream that transforms all items using the given transform function and then discards all items that are null or undefined.

    Type Parameters

    • U

    Parameters

    • transform: (item: T) => undefined | null | U

      A function that maps each item to a nullable item of an arbitrary type. Return values null and undefined will not be included in the returned stream.

    Returns Stream<NonNullable<U>>

    import { Stream } from "apprt-streams/Stream";
    const persons = [{ age: 7 }, { age: 18 }, { age: 21 }];
    const adultAges = Stream.from(persons).filterMap(
    (person) => person.age >= 18 ? person.age : undefined
    ).toArray(); // [18, 21]
  • Searches the elements in this stream for an item for which the predicate returns true. Returns the item on success or undefined if no item was found.

    Type Parameters

    • U

    Parameters

    • predicate: (item: T) => item is U

    Returns U

  • Searches the elements in this stream for an item for which the predicate returns true. Returns the item on success or undefined if no item was found.

    Parameters

    • predicate: (item: T) => boolean

    Returns undefined | T

  • Returns the first item in this stream, or undefined if the stream is empty.

    Returns undefined | T

  • Returns a stream that flattens its input by one layer (elements that are iterable become multiple elements of the new stream).

    Returns Stream<FlatValue<T>>

    import { Stream } from "apprt-streams/Stream";
    const items = [[1], [2, 3]];
    const result = Stream.from(items).flat().toArray(); // [1, 2, 3]
  • Invokes the callback for every item in the stream. Works exactly like Array's forEach function, with the exception that no source array is passed.

    Parameters

    • callback: (item: T, index: number) => void

    Returns void

  • Returns a stream that groups adjacent elements for which the predicate returns true into arrays.

    This is different from groupBy because it allows arbitrary conditions for grouping. However, only elements next to each other can belong to a group. A new group is started whenever an element is encountered that does not belong to the current group.

    Parameters

    • predicate: (left: T, right: T) => boolean

      A function that returns true if left and right belong to the same group.

    Returns Stream<T[]>

    const numbers = [1, 2, 4, 3, 0];
    const grouped = Stream.from(numbers)
    .groupAdjacent((l, r) => Math.abs(l - r) <= 1) // close items belong to the same group
    .toArray(); // [[1, 2], [4, 3], [0]]
  • Groups items together for which keyFunc returns the same value. The keyFunc function should generate keys that are supported by JavaScript's Map type.

    NOTE: This function reads the entire stream into memory and stores items in an internal map, which may be inefficient for very large datasets.

    Type Parameters

    • U

    Parameters

    • keyFunc: (item: T) => U

      Given an item from the stream, returns a group key for that item. All items with an equal group key end up in the same group.

    Returns Stream<[U, T[]]>

    import { Stream } from "apprt-streams/Stream";
    const persons = [
    { name: "A", age: 18 },
    { name: "B", age: 18 },
    { name: "C", age: 20 },
    ];
    const byAge = Stream.from(persons)
    .groupBy((p) => p.age)
    .toObject(); // { 18: [person A, person B], 20: [person C] }
  • Returns true if this stream contains an element that compares equal to item. Comparisons use strict equality (===).

    Parameters

    • item: T

    Returns boolean

  • Returns true if there is at least one element in this stream, false otherwise.

    Returns boolean

  • Joins all elements of this stream together into a string. Individual elements will be converted to string (via String(elements)) and separated by separator.

    Parameters

    • separator: string = ","

      The separator to use between two elements. Defaults to ",".

    Returns string

  • Returns the last item in this stream, or undefined if this stream is empty.

    NOTE: This iterates over the entire stream in order to find the last element. Be aware of the performance implications: the function should not be called repeatedly (cache the result instead) and you should ensure that your stream is finite.

    Returns undefined | T

  • Returns a stream that maps all elements of the input by using the provided transform function.

    Type Parameters

    • U

    Parameters

    • transform: (item: T) => U

      A function that maps each item to a another item of an arbitrary type.

    Returns Stream<U>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2];
    const result = Stream.from(items).map(n => n + 1).toArray(); // [2, 3]
  • Returns the largest stream item according to the given compareFunc. If multiple candidates for the largest element compare equal to each other, the first of those items (according to the stream order) will be returned.

    Parameters

    • OptionalcompareFunc: (left: T, right: T) => number

      Given two items left and right, returns < 0 if left < right, > 0 if left > right and 0 otherwise. When not specified, items are compared using standard < and > (which might be useless, e.g. when items are objects or arrays).

    Returns undefined | T

    the largest item or undefined if the stream is empty.

  • Like max(), but compares keys derived from the stream's items instead of the items themselves. The item with the largest key will be returned (or undefined if the stream is empty).

    Type Parameters

    • U

    Parameters

    • keyFunc: (value: T) => U

      Given an item, returns a sort key for comparison during sorting. This function should be fast, because it will be invoked at least once for every element.

    • OptionalcompareFunc: (left: U, right: U) => number

      Given two keys derived by keyFunc, returns < 0 if left < right, > 0 if left > right and 0 otherwise. When not specified, keys are compared using standard < and > (which might be useless, e.g. when keys are objects or arrays).

    Returns undefined | T

    the largest item or undefined if the stream is empty.

  • Like max, but returns the smallest item instead.

    Parameters

    • OptionalcompareFunc: (left: T, right: T) => number

    Returns undefined | T

  • Like maxBy, but returns the item with the smallest key instead.

    Type Parameters

    • U

    Parameters

    • keyFunc: (value: T) => U
    • OptionalcompareFunc: (left: U, right: U) => number

    Returns undefined | T

  • Invokes the reduceFunc for every element of the stream in order to provide a single return value. Works exactly like Array's reduce function, with the exception that no source array is passed.

    Parameters

    • reduceFunc: (currentValue: T, item: T, index: number) => T

    Returns T

  • Invokes the reduceFunc for every element of the stream in order to provide a single return value. Works exactly like Array's reduce function, with the exception that no source array is passed.

    Type Parameters

    • U

    Parameters

    • reduceFunc: (currentValue: U, item: T, index: number) => U
    • initial: U

    Returns U

  • Returns a stream that repeats its contents count times.

    Parameters

    • count: number

      the number of repetitions

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = ["a", "b"];
    const repeated = Stream.from(items).repeat(2).toArray(); // ["a", "b", "a", "b"];
  • Returns a stream that consists of all elements of this stream, in reversed order.

    NOTE: This function reads the entire stream into memory in order to reverse the item order. This may be inefficient for very large datasets.

    Returns Stream<T>

    const items = Stream.integers(4).reverse().toArray(); // [3, 2, 1, 0]
    
  • Returns a stream that skips the first count elements of its input.

    Parameters

    • count: number

      the number of items to skip

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2, 3];
    const result = Stream.from(items).skip(1).toArray(); // [2, 3]
  • Returns a stream that skips elements while the predicate returns true. Once the predicate returns false, all the following items will be included in the returned stream.

    Parameters

    • predicate: (item: T) => boolean

      A predicate determining if items shall be skipped. Once the predicate returns false, all remaining items are included in the returned stream.

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2, 3, 4, -1, -2, -3];
    const result = Stream.from(items).skipWhile((n) => n < 4).toArray(); // [4, -1, -2, -3]
  • Determines if the given condition matches to at least one of the stream's items.

    Parameters

    • predicate: (item: T) => boolean

      Returns true if any item in the stream fulfills the given predicate, false otherwise.

    Returns boolean

  • Returns a stream that has all its elements sorted according to the given compareFunc. The comparison function is optional, the Array sort behavior will be used by default when the function is omitted. The function must behave as expected by the Array.sort() method.

    See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

    NOTE: This function reads the entire stream into memory and stores all elements in an array to be able to sort it. This may be inefficient for very large datasets.

    Parameters

    • OptionalcompareFunc: (left: T, right: T) => number

      Given two elements left and right, returns < 0 if left < right, > 0 if right > left and 0 otherwise. When not specified, elements are compared using standard < and > (which might be useless, e.g. when keys are objects or arrays).

    Returns Stream<T>

  • Like sort(), but sorts by comparing keys derived from the stream's items.

    NOTE: This function reads the entire stream into memory and stores all elements in an array to be able to sort it. This may be inefficient for very large datasets.

    Type Parameters

    • U

    Parameters

    • keyFunc: (item: T) => U

      Given an item, returns a sort key for comparison during sorting. This function should be fast, because it will be invoked at least once for every element.

    • OptionalcompareFunc: (leftKey: U, rightKey: U) => number

      Given two keys derived by keyFunc, returns < 0 if left < right, > 0 if right > left and 0 otherwise. When not specified, keys are compared using standard < and > (which might be useless, e.g. when keys are objects or arrays).

    Returns Stream<T>

    A new stream of sorted elements.

    const items = [
    { name: "A", age: 18 },
    { name: "B", age: 28 },
    { name: "C", age: 17 }
    ];
    const sorted = Stream.from(items).sortBy(item => item.age).toArray();
  • Returns a stream that limits the input to at most count elements.

    Parameters

    • count: number

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2, 3];
    const result = Stream.from(items).take(1).toArray(); // [1]

    the number of elements to include in the returned stream

  • Returns a stream over the input that produces values while the predicate returns true. The stream will be cut off when the predicate returns false for the first time.

    Parameters

    • predicate: (item: T) => boolean

      Determines when including items in the returned stream shall be stopped.

    Returns Stream<T>

    import { Stream } from "apprt-streams/Stream";
    const items = [1, 2, 3, 4, -1, -2, -3];
    const result = Stream.from(items).takeWhile((n) => n < 4).toArray(); // [1, 2, 3]
  • Gathers all elements of this stream into an array.

    Returns T[]

    import { Stream } from "apprt-streams/Stream";
    const array = Stream.integers(3).toArray(); // [0, 1, 2]
  • Gathers the elements of this stream into a map. The elements must be [key, value] pairs.

    Note: elements are inserted into the map in the order they occur in the stream. Iterating over the map will yield the same order because maps maintain their insertion order.

    Parameters

    • this: T extends [any, any] ? Stream<T> : never

    Returns T extends [K, V] ? Map<K, V> : never

    import { Stream } from "apprt-streams/Stream";
    const map = Stream.from(["a", "b", "c"])
    .map((v) => [v, v + "!"])
    .toMap(); // // a -> a!, b -> b!, c -> c!
  • Gathers all elements of this stream into an object. The elements must be [key, value] pairs, and the keys must be strings, symbols or numbers.

    Parameters

    • this: T extends [PropertyKey, any] ? Stream<T> : never

    Returns T extends [K, V] ? [K] extends [PropertyKey] ? Record<K<K>, V> : never : never

    import { Stream } from "apprt-streams/Stream";
    const object = Stream.from(["a", "b", "c"])
    .map((v) => [v, v + "!"])
    .toObject(); // { a: "a!", b: "b!", c: "c!"}
  • Gathers all elements of this stream into a set.

    Note: elements are inserted into the set in the order they occur in the stream. Iterating over the set will yield the same order because sets maintain their insertion order.

    Returns Set<T>

    import { Stream } from "apprt-streams/Stream";
    const set = Stream.integers(3).toSet(); // set of 0, 1, 2
  • Returns a stream that consists of all elements of this stream, with duplicates removed. The relative order of the remaining elements is preserved.

    NOTE: This function reads the entire stream into memory and stores all elements in a Set for de-duplication. This may be inefficient for very large datasets.

    Returns Stream<T>

    A new stream with unique items.

    const items = [
    {age: 1},
    {age: 2},
    {age: 3},
    {age: 1},
    {age: 3},
    {age: 3}
    ];
    const result = Stream.from(items).map(i => i.age).unique().toArray();
    // result == [1, 2, 3]
  • Zips the given iterables with this with the zipLongest algorithm (see static zipLongest function for details). The length of the resulting stream is the maximum length of all iterables, with empty positions filled with undefined.

    Type Parameters

    • Ts extends Iterable[] | [Iterable]

    Parameters

    • ...iterables: Ts

      a series of iterables who's items will be zipped next to the items of this.

    Returns Stream<[undefined | T, ...ZipLongestValue<Ts>[]]>

  • Zips the given iterables with this (see static zip function for details). The length of the resulting stream is the minimum length of all iterables.

    Type Parameters

    • Ts extends Iterable[] | [Iterable]

    Parameters

    • ...iterables: Ts

      a series of iterables who's items will be zipped next to the items of this.

    Returns Stream<[T, ...MapIterableValues<Ts>[]]>