Interface Stream<T>

A stream is a thin wrapper over an iterable, providing intermediate and terminal operations to manipulate data. Like iterables, streams respect the order of items; unless explicitly specified otherwise, operations consume and transform items in their original order. Streams are lazy: all computations are triggered only during terminal operations.

A stream can be understood as a function over an iterable. Intermediate operations return new functions with the current stream as input, while terminal operations capture the input, evaluate the chain of functions, and return data.

stream(1, 2, 3, 4)           // factory
.filter(i => i % 2 === 0) // intermediate
.map(i => -i) // intermediate
.toArray() // terminal => [-2, -4]

Streams are stateless: they store only a reference to the input. This means streams can be iterated multiple times, and each time, the stream evaluates the input as it existed at the moment the terminal operation was invoked.

const input = [10, 20, 30]
const s = stream(input)
.map(i => i + 1)

s.toArray() // => [11, 21, 31]

input.push(40)
s.toArray() // => [11, 21, 31, 41]

During evaluation, streams produce as little intermediate data as possible. For example, Stream.map does not copy input data; instead, it retrieves upstream data one by one and yields mapped items value by value. Some operations do require creating intermediate data structures, such as Stream.shuffle and Stream.sortBy. In such cases, downstream steps maximize the benefit of having a random-access array that can be modified.

stream(30, 20, 10, 0)
.map(i => i + 1) // does not copy data, maps on evaluation
.sortBy(i => i) // copies data to a new array and sorts it
.at(2) // accesses index 2 in the sorted array
.get() // => 21
interface Stream<T> {
    "[iterator]"(): Iterator<T, undefined, any>;
    at(index: number): Optional<T>;
    awaitAll(): Promise<T extends PromiseLike<E> ? E[] : T[]>;
    butLast(): Stream<T>;
    concat<U = T>(...items: U[]): Stream<T | U>;
    concatAll<U = T>(items: Iterable<U, any, any>): Stream<T | U>;
    distinctBy(getKey: (item: T, index: number) => any): Stream<T>;
    drop(n: number): Stream<T>;
    dropLast(n: number): Stream<T>;
    dropLastWhile(predicate: (item: T, index: number) => boolean): Stream<T>;
    dropWhile(predicate: (item: T, index: number) => boolean): Stream<T>;
    equals(other: Iterable<T, any, any>): boolean;
    every(predicate: (item: T, index: number) => boolean): boolean;
    filter(predicate: (item: T, index: number) => boolean): Stream<T>;
    filter<U>(predicate: (item: T, index: number) => item is U): Stream<U>;
    find(predicate: (item: T, index: number) => boolean): Optional<T>;
    findIndex(predicate: (item: T, index: number) => boolean): Optional<number>;
    findLast(predicate: (item: T, index: number) => boolean): Optional<T>;
    findLastIndex(
        predicate: (item: T, index: number) => boolean,
    ): Optional<number>;
    flat<D extends number = 1>(depth?: D): Stream<FlatIterable<T, D>>;
    flatMap<U>(
        mapper: (item: T, index: number) => Iterable<U, any, any>,
    ): Stream<U>;
    forEach(effect: (item: T, index: number) => void): void;
    forEachUntil(
        effect: (item: T, index: number) => undefined | boolean | void,
    ): boolean;
    groupBy<K>(getKey: (item: T, index: number) => K): Stream<[K, T[]]>;
    groupByToMap<K>(getKey: (item: T, index: number) => K): Map<K, T[]>;
    head(): Optional<T>;
    join(sep?: string): string;
    join(spec: { leading?: boolean; sep: string; trailing?: boolean }): string;
    joinBy(getSep: (left: T, right: T, leftIndex: number) => string): string;
    last(): Optional<T>;
    map<U>(mapper: (item: T, index: number) => U): Stream<U>;
    mapNullable<U>(
        mapper: (item: T, index: number) => undefined | null | U,
    ): Stream<U>;
    peek(effect: (item: T, index: number) => void): Stream<T>;
    randomItem(): Optional<T>;
    reduce(
        reducer: (accumulator: T, currentItem: T, currentIndex: number) => T,
    ): Optional<T>;
    reduce<U>(
        reducer: (accumulator: U, currentItem: T, currentIndex: number) => U,
        initialValue: U,
    ): U;
    reduceRight(
        reducer: (accumulator: T, currentItem: T, currentIndex: number) => T,
    ): Optional<T>;
    reduceRight<U>(
        reducer: (accumulator: U, currentItem: T, currentIndex: number) => U,
        initialValue: U,
    ): U;
    reverse(): Stream<T>;
    shuffle(): Stream<T>;
    single(): Optional<T>;
    size(): number;
    slice(start?: number, end?: number): Stream<T>;
    some(predicate: (item: T, index: number) => boolean): boolean;
    sort(compareFn?: (a: T, b: T) => number): Stream<T>;
    sortBy(getComparable: (item: T) => string | number | boolean): Stream<T>;
    splice<U = T>(
        start: number,
        deleteCount?: number,
        ...items: U[],
    ): Stream<T | U>;
    splitWhen(
        isSplit: (left: T, right: T, leftIndex: number) => boolean,
    ): Stream<T[]>;
    tail(): Stream<T>;
    take(n: number): Stream<T>;
    takeLast(n: number): Stream<T>;
    takeLastWhile(predicate: (item: T, index: number) => boolean): Stream<T>;
    takeRandom(n: number): Stream<T>;
    takeWhile(predicate: (item: T, index: number) => boolean): Stream<T>;
    toArray(): T[];
    toObject(): T extends readonly [string | number | symbol, any]
        ? { [key in string | number | symbol]: T<T>[1] }
        : unknown;
    toSet(): Set<T>;
    transform<U>(
        operator: (input: Iterable<T, any, any>) => Iterator<U, any, any>,
    ): Stream<U>;
    transformToOptional<U>(
        operator: (input: Iterable<T, any, any>) => Iterator<U, any, any>,
    ): Optional<U>;
    with(index: number, value: T): Stream<T>;
    zip<U>(other: Iterable<U, any, any>): Stream<[T, U]>;
    zipAdjacent<N extends number>(n: N): Stream<TupleOf<T, N>>;
    zipStrict<U>(other: Iterable<U, any, any>): Stream<[T, U]>;
    zipWithIndex(): Stream<[T, number]>;
    zipWithIndexAndLen(): Stream<[T, number, number]>;
    zipWithNext(): Stream<[T, T]>;
}

Type Parameters

  • T

    The type of elements in this stream

Hierarchy

  • Iterable<T, undefined>
    • Stream

Methods

  • Returns an iterator that yields the items of this stream.

    Returns Iterator<T, undefined, any>

    An iterator over the items of this stream.

  • Returns an optional that resolves to the element at the specified index position in this stream. A negative index counts from the last item (e.g., -1 refers to the last item, -2 to the second-to-last item, and so on). If the specified position does not exist, the optional resolves to empty.

    Parameters

    • index: number

      A zero-based position for the desired item, or a negative position to count from the end of the stream, converted to an integer.

    Returns Optional<T>

    An Optional containing the item at the specified position, or empty if no such position exists.

  • Calls Promise.all() on the items in this stream and returns the resulting promise. If the items in this stream are of type Promise<E>, the result will be of type Promise<E[]>. For more complex cases, refer to the MDN documentation.

    Returns Promise<T extends PromiseLike<E> ? E[] : T[]>

    A Promise resolving to an array of results, where the type depends on whether the items in the stream are promises.

  • Returns a stream containing all items of this stream except the last one. If this stream is empty or contains only a single item, the resulting stream will also be empty.

    Returns Stream<T>

    A Stream containing all but the last item of this stream.

  • Returns a stream containing all items of this stream, followed by the provided items.

    Type Parameters

    • U = T

      The type of the items to append, defaults to T - the item type of this stream.

    Parameters

    • ...items: U[]

      The items to append to the end of the stream.

    Returns Stream<T | U>

    A Stream with the original items of this stream and the appended items.

  • Returns a stream containing all items of this stream, followed by all items provided by the items iterable.

    Type Parameters

    • U = T

      The type of the items to append, defaults to T - the item type of this stream.

    Parameters

    • items: Iterable<U, any, any>

      An iterable whose items will be appended to the end of this stream.

    Returns Stream<T | U>

    A Stream with the original items of this stream followed by the items from the provided iterable.

  • Returns a stream containing only the elements of this stream for which getKey returns unique keys. If multiple items produce the same key, only the first such item is included in the result stream.

    The implementation uses a Set under the hood, meaning that keys are compared using the SameValueZero algorithm.

    Parameters

    • getKey: (item: T, index: number) => any

      A function that extracts a key from each item to determine uniqueness. Receives an item and its index in the stream.

    Returns Stream<T>

    A Stream containing only the distinct items based on their keys.

  • Returns a stream containing all items except the first n items of this stream. If the stream contains n or fewer items, the resulting stream will be empty.

    Parameters

    Returns Stream<T>

    A Stream containing all items except the first n.

  • Returns a stream containing all items except the last n items of this stream. If the stream contains n or fewer items, the resulting stream will be empty.

    Parameters

    Returns Stream<T>

    A Stream containing all items except the last n.

  • Returns a stream containing all items of this stream after dropping the trailing items that satisfy the given predicate. Items are checked from the end of the stream backward. Once an item does not match the predicate, all preceding items and that item are included in the resulting stream.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function invoked for each item, with the following parameters: - item - The current item in the stream. - index - The index of the current item in the stream, starting from 0. The function should return true to drop the item or false to stop dropping.

    Returns Stream<T>

    A Stream containing the remaining items after dropping the trailing items that satisfy the predicate.

  • Returns a stream containing all items of this stream after dropping the leading items that satisfy the given predicate. Once an item does not match the predicate, that item and all subsequent items are included in the resulting stream.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function invoked for each item, with the following parameters: - item - The current item in the stream. - index - The index of the current item in the stream, starting from 0. The function should return true to drop the item or false to stop dropping.

    Returns Stream<T>

    A Stream containing the remaining items after dropping the leading items that satisfy the predicate.

  • Returns true if the other iterable contains the same number of items as this stream and all corresponding items are equal using the === operator.

    Parameters

    • other: Iterable<T, any, any>

      An iterable to test for equality with this stream.

    Returns boolean

    true if the iterables are equal in length and item-wise equality, otherwise false.

  • Returns true if the predicate returns true for all items of this stream; returns false otherwise. For an empty stream, the result is true.

    This is a short-circuiting operation, meaning it stops processing items as soon as the predicate returns false for any item.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function to test each item in the stream. Receives an item and its index in the stream.

    Returns boolean

    true if all items satisfy the predicate or the stream is empty, otherwise false.

  • Returns a stream containing only the items of this stream that match the provided predicate.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function to test each item in the stream. Receives an item and its index in the stream.

    Returns Stream<T>

    A Stream containing the items that satisfy the predicate.

  • Returns a stream with a possibly narrowed type, containing only the items of this stream that match the provided predicate. For example, this can be used to filter out null values from the stream.

    streamOf('a', null, 'b')
    .filter<string>(item => typeof item === 'string')
    .toArray() satisfies string[]

    Type Parameters

    • U

    Parameters

    • predicate: (item: T, index: number) => item is U

      A type predicate function used to test items and narrow their type.

    Returns Stream<U>

    A Stream containing only the items that satisfy the predicate.

  • Returns an Optional which resolves to the first item that matches the predicate, or to empty if no such item is found.

    Parameters

    • predicate: (item: T, index: number) => boolean

      The function to test each item in the stream. Receives an item and its index in the stream.

    Returns Optional<T>

    An Optional that contains the first matching item or is empty if no item matches.

  • Returns an Optional containing the index of the first item in this stream that satisfies the given predicate. If no such item is found, the optional resolves to empty.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function that tests each item in the stream. It receives the current item and its index as arguments and should return true for the desired item.

    Returns Optional<number>

    An Optional containing the index of the first matching item, or empty if no item matches the predicate.

  • Returns an Optional which resolves to the last item that matches the predicate, or to empty if no such item is found.

    Parameters

    • predicate: (item: T, index: number) => boolean

      The function to test each item in the stream. Receives an item and its index in the stream.

    Returns Optional<T>

    An Optional that contains the last matching item or is empty if no item matches.

  • Returns an Optional containing the index of the last item in this stream that satisfies the given predicate. If no such item is found, the optional resolves to empty.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function that tests each item in the stream. It receives the current item and its index as arguments and should return true for the desired item.

    Returns Optional<number>

    An Optional containing the index of the last matching item, or empty if no item matches the predicate.

  • Returns a stream with the following behavior:

    • Non-iterable items are included in the resulting stream as is.
    • Iterable items are flattened up to the specified depth and included in the resulting stream.

    Type Parameters

    • D extends number = 1

    Parameters

    • Optionaldepth: D

      The depth of flattening. Defaults to 1.

    Returns Stream<FlatIterable<T, D>>

    A Stream containing the flattened items.

  • Returns a stream with the following behavior:

    1. Iterates over the items in this stream.
    2. Applies the mapper function to each item.
    3. Flattens and chains together all results returned by the mapper function into a single-level stream.

    This operation is also known as chain.

    Type Parameters

    • U

      The type of items produced by the mapper function, and type of items in the resulting stream.

    Parameters

    • mapper: (item: T, index: number) => Iterable<U, any, any>

      A function that transforms each item in the stream into an iterable of items to be flattened. Receives an item and its index in the stream.

    Returns Stream<U>

    A new Stream containing all items produced by the mapper function, flattened into a single level.

  • Invokes effect for each item of this stream.

    Parameters

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

      The effect to apply to each item. Receives an item and its index in the stream.

    Returns void

  • Invokes the specified effect function for each item in this stream until the effect function returns true.

    Parameters

    • effect: (item: T, index: number) => undefined | boolean | void

      A function to apply to each item in the stream. The function can return a value that determines whether iteration should stop. Receives an item and its index in the stream.

    Returns boolean

    true if the iteration was stopped because the effect function returned true, otherwise false.

  • Returns a stream whose elements are [key, items[]] pairs. Keys are derived using the getKey function applied to the items in this stream. items are arrays of stream elements that produced the same key.

    This method uses a Map internally for grouping, meaning that keys are compared using the SameValueZero algorithm.

    The method works similar to Map.groupBy().

    Type Parameters

    • K

    Parameters

    • getKey: (item: T, index: number) => K

      A function to derive the key for each item. The function receives the item and its index in the stream.

    Returns Stream<[K, T[]]>

    A Stream of [key, items[]] pairs, where key is a derived key and items[] is an array of elements associated with that key.

  • Collects the items of this stream into a Map. Keys are generated using the provided getKey function applied to each item in the stream.

    Items that produce the same key (as determined by the Map's key equality) are grouped into an array and stored as the value corresponding to that key.

    The method works similar to Map.groupBy().

    Type Parameters

    • K

    Parameters

    • getKey: (item: T, index: number) => K

      A function to derive the key for each item. The function receives the item and its index in the stream.

    Returns Map<K, T[]>

    A Map where each key is associated with an array of items that produced the same key.

  • Returns an optional that resolves to the first item of this stream if the stream contains any items, or resolves to empty otherwise.

    Returns Optional<T>

    An Optional containing the first item or empty.

  • Concatenates the items of this stream, inserting sep between them. Items are coerced to strings using the String function (without new).

    Parameters

    • Optionalsep: string

      A string to insert between items. Defaults to ",".

    Returns string

    A string representing the concatenated stream items.

  • Concatenates the items of this stream, inserting spec.sep between them. Additionally, can insert spec.leading and spec.trailing strings before and after the result, if provided. Items are coerced to strings using the String function (without new).

    Parameters

    • spec: { leading?: boolean; sep: string; trailing?: boolean }

      An object specifying:

      • sep: A string to insert between items.
      • leading: A string to prepend to the result (optional).
      • trailing: A string to append to the result (optional).

    Returns string

    A string representing the concatenated stream items.

  • Like join but retrieves the separator by calling getSep for each pair of adjacent items.

    @@param getSep - A function that returns the separator for each pair of adjacent items. Receives the left item, the right item, and the index of the left item in the stream.

    Parameters

    • getSep: (left: T, right: T, leftIndex: number) => string

    Returns string

    A string representing the concatenated stream items with custom separators.

  • Returns an optional resolving to the last item of this stream if it's nonempty, or resolving to empty otherwise.

    Returns Optional<T>

    An Optional resolving to the last item if the stream is nonempty, or to empty otherwise.

  • Returns a stream where each item is transformed by mapper.

    Type Parameters

    • U

    Parameters

    • mapper: (item: T, index: number) => U

      A function to transform each item. Receives an item and its index in the stream.

    Returns Stream<U>

    A new Stream containing the transformed items.

  • Returns a stream whose items are transformed by mapper, with null and undefined results filtered out.

    Type Parameters

    • U

    Parameters

    • mapper: (item: T, index: number) => undefined | null | U

      The function to transform each item. Receives an item and its index in the stream.

    Returns Stream<U>

    A new Stream with the non-null and non-undefined transformed items.

  • Returns a stream that executes an effect for each item, returning the item unchanged. This method can be used, for example, to mutate items in place.

    Parameters

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

      The effect to execute on each item. Receives an item and its index in the stream.

    Returns Stream<T>

    A new Stream with the same items, after executing the effect.

  • Returns an optional that resolves to a random item from this stream, or resolves to empty if the stream is empty. The implementation uses the pseudo-random Math.random(), which means it's not suitable for cryptographic purposes.

    Returns Optional<T>

    An Optional containing a random item from the stream, or empty if the stream is empty.

  • Returns an optional with the following behavior:

    • Resolves to empty if the stream is empty.
    • Resolves to the single item if the stream contains exactly one item.
    • Resolves to the final value produced by repeatedly applying the reducer function. The reducer is first applied to the items at index 0 and index 1, then to the result of the previous invocation and the item at the next index, and so on.

    Parameters

    • reducer: (accumulator: T, currentItem: T, currentIndex: number) => T

      A function that reduces the stream's items. It receives the following parameters: - accumulator - The result of the previous reducer invocation, or, for the first invocation, the item at index 0. - currentItem - The current item of the stream. For the first invocation, the item at index 1. - currentIndex - The index of the current item in the stream. For the first invocation, this is 1.

    Returns Optional<T>

    An Optional containing the reduced value, or empty if the stream is empty.

  • If this stream is empty, returns initialValue. Otherwise, applies reducer to initialValue and the item at index 0, then applies reducer to the previously returned result and the item at index 1, and so on, returning the result from the last reducer invocation.

    Type Parameters

    • U

    Parameters

    • reducer: (accumulator: U, currentItem: T, currentIndex: number) => U

      The function to reduce items. Takes the following parameters: - accumulator - The result of the previous reducer invocation, or, for the first invocation, initialValue. - currentItem - The current item of the stream. - currentIndex - The index of the current item in the stream. For the first invocation, this is 0.

    • initialValue: U

      The initial value for the reduction process.

    Returns U

    The result of the reduction process.

  • Returns an optional with the following behavior:

    • If this stream is empty, resolves to empty.
    • If this stream has one item, resolves to that item.
    • Otherwise, applies reducer to the item at index size - 1 and the item at index size - 2, then applies reducer to the previously returned result and the item at index size - 3, and so on, resolving to the value returned by the final reducer invocation.

    Parameters

    • reducer: (accumulator: T, currentItem: T, currentIndex: number) => T

      The function to reduce items. Takes the following parameters: - accumulator - The result of the previous reducer invocation, or, for the first invocation, the item at index size - 1. - currentItem - The current item of the stream. - currentIndex - The index of the current item in the stream, starting from size - 2 and decreasing toward 0.

    Returns Optional<T>

    An Optional containing the result of the reduction, or empty if the stream is empty.

  • If this stream is empty, returns initialValue. Otherwise, applies reducer to initialValue and the item at the index size - 1, then applies reducer to the previously returned result and the item at index size - 2, and so on, returning the result from the final reducer invocation.

    Type Parameters

    • U

    Parameters

    • reducer: (accumulator: U, currentItem: T, currentIndex: number) => U

      The function to reduce items. Takes the following parameters: - accumulator - The result of the previous reducer invocation, or, for the first invocation, initialValue. - currentItem - The current item of the stream. - currentIndex - The index of the current item in the stream, starting from the index size - 1 and decreasing toward 0.

    • initialValue: U

      The initial value for the reduction process.

    Returns U

    The result of the reduction process.

  • Returns a stream whose elements are the elements of this stream in reversed order.

    Returns Stream<T>

    A new Stream with the elements in reversed order.

  • Returns a stream whose elements are the elements of this stream in random order. Uses the pseudo-random Math.random(), which means it is not suitable for cryptographic purposes.

    Returns Stream<T>

    A new Stream with the elements in random order.

  • Returns an optional that resolves to an item if this stream contains only one item; otherwise, it resolves to empty.

    Returns Optional<T>

    An Optional resolving to the single item or to empty.

  • Returns the number of items in this stream.

    Returns number

    The size of this stream.

  • Returns a stream containing a portion of this stream, determined by the start and end indices. The resulting stream includes the items starting from the start index up to, but not including, the end index.

    If no start is specified, the slice begins at index 0. If no end is specified, the slice ends at the last item in the stream. Negative indices can be used for both start and end to indicate positions from the end of the stream, where -1 refers to the last item, -2 refers to the second-to-last item, and so on.

    The method's behavior aligns with Array.slice().

    Parameters

    • Optionalstart: number

      The zero-based index at which to begin the slice, converted to an integer. Defaults to 0.

    • Optionalend: number

      The zero-based index before which to end the slice, converted to an integer. Defaults to the size of the stream.

    Returns Stream<T>

    A Stream containing the specified portion of this stream.

  • Returns true if the predicate returns true for any item of this stream; returns false otherwise. This is a short-circuiting operation, meaning it skips the remaining items once the predicate returns true for any item.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function to test each item. Receives an item and its index in the stream.

    Returns boolean

    true if any item satisfies the predicate, false otherwise.

  • Returns a stream whose items are sorted items of this stream. The implementation relies on Array.sort().

    Parameters

    • OptionalcompareFn: (a: T, b: T) => number

      Comparison function with semantics described in MDN here. If not provided, the underlying Array.sort() will convert items to strings and compare them lexicographically.

    Returns Stream<T>

    A Stream with sorted items.

  • Returns a stream with items of this stream ordered by the value returned by getComparable. The returned values are then compared with > and <. The implementation relies on Array.sort().

    Parameters

    • getComparable: (item: T) => string | number | boolean

      A function that, given an item, returns a comparable value. The returned value is not cached, so it is recommended not to perform heavy computations in this function.

    Returns Stream<T>

    A Stream with items ordered by the comparable value.

  • Removes or replaces existing items in the stream and/or adds new items in their place. This method is similar to Array.prototype.splice, but instead of modifying the input in place and returning removed items, it leaves the input unchanged and returns a new stream reflecting the changes.

    Type Parameters

    • U = T

      The type of the items to add, defaults to T - the item type of this stream.

    Parameters

    • start: number

      The zero-based index at which to begin changing the stream, converted to an integer. A negative value counts from the end of the stream, with -1 referring to the last item.

      • If positive start exceeds the length of the stream, no items are deleted, and the provided items are added to the end of the stream.
      • If negative start is less than the negative size of the stream, 0 is used.
    • OptionaldeleteCount: number

      The number of items to remove from the stream, converted to an integer.

      • If omitted or Infinity, all items from start to the end of the stream are removed.
      • If 0, negative, or explicitly null or undefined, no items are removed.
    • ...items: U[]

      The items to add to the stream starting at start. If no items are provided, the method only removes items.

    Returns Stream<T | U>

    A stream containing the items after removing or replacing items.

    const original = stream([1, 2, 3, 4, 5])
    const modified = original.splice(1, 2, 8, 9) // => Stream of [1, 8, 9, 4, 5]
  • Returns a stream whose items are groups of adjacent items from this stream for which isSplit returned false. In other words, given all items as a sequence, it splits them between items for which isSplit returns true.

    Parameters

    • isSplit: (left: T, right: T, leftIndex: number) => boolean

      A function to check if the items sequence should be split between left and right items. Receives the index of the left item as a 3rd parameter.

    Returns Stream<T[]>

    A Stream containing groups of adjacent items.

  • Returns a stream that contains all but the first item of this stream. If the stream is empty or contains only one item, the returned stream will be empty.

    Returns Stream<T>

    A Stream containing all but the first item.

  • Returns a stream containing no more than the first n items of this stream.

    Parameters

    Returns Stream<T>

    A Stream containing no more than the first n items.

  • Creates a stream containing no more than the last n items of this stream.

    Parameters

    Returns Stream<T>

    A Stream containing the last n items.

  • Returns a stream containing the trailing items of this stream that satisfy the given predicate. Once an item does not match the predicate, this item and all preceding items are excluded from the resulting stream.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function invoked with each item and its index. Returns true to include the item in the resulting stream, or false to stop iterating.

    Returns Stream<T>

    A Stream containing the trailing items that satisfy the given predicate.

  • Returns a stream containing no more than n random items from this stream. The result is sampled without replacement, meaning each item from this stream appears no more than once in the result. The implementation uses pseudo-random Math.random(), so it is not suitable for cryptographic purposes.

    Parameters

    Returns Stream<T>

    A Stream containing up to n random items.

  • Returns a stream containing the leading items of this stream that satisfy the given predicate. Once an item does not match the predicate, this item and all subsequent items are excluded from the resulting stream.

    Parameters

    • predicate: (item: T, index: number) => boolean

      A function invoked with each item and its index. Returns true to include the item in the resulting stream, or false to stop iterating.

    Returns Stream<T>

    A Stream containing the leading items that satisfy the given predicate.

  • Returns the items of the stream as an array.

    Returns T[]

    An array containing the items of the stream.

  • Converts a stream of [key, value] pairs where key is string, number, or symbol, to an object. If a key appears multiple times in the stream, only the last [key, value] pair will be included in the result object. If the elements of the stream are not [key, value] pairs as described, an error will be thrown.

    In TypeScript, you may need to use as const after each tuple to help TypeScript infer the correct tuple types:

    stream(['a', 'b'] as const)
    .map(key => [key, 0] as const)
    .toObject() // => type is {a: 0, b: 0}

    stream(['a', 'b'])
    .map(key => [key, 0] as const)
    .toObject() // => type is {[p: string]: 0}

    stream(['a', 'b'])
    .map(key => [key, 0])
    .toObject() // => type is unknown

    Returns T extends readonly [string | number | symbol, any]
        ? { [key in string | number | symbol]: T<T>[1] }
        : unknown

    An object where the keys are from the stream's [key, value] pairs and the values are the corresponding values from those pairs.

    An error if the elements of the stream are not [key, value] pairs.

  • Returns the items of the stream as a set.

    Returns Set<T>

    A set containing the items of the stream.

  • Extension method to apply an arbitrary operator to the stream. An operator is passed an iterable that yields this stream's items, and it must return an iterator to be used in the next step. The easiest way to achieve this is by using generators:

    stream(1, 2, 3, 4, 5, 6)
    .transform(function* (items) {
    for (const item of items) {
    if (item % 3 === 0) yield item;
    }
    }).toArray(); // => [3, 6]

    Type Parameters

    • U

    Parameters

    • operator: (input: Iterable<T, any, any>) => Iterator<U, any, any>

      A function that receives an iterable yielding this stream's items and is expected to return an iterator for the downstream step.

    Returns Stream<U>

    A Stream based on the transformed items.

  • Like transform, but returns an optional that discards all items except the first one yielded by the iterator returned by the operator.

    Type Parameters

    • U

    Parameters

    • operator: (input: Iterable<T, any, any>) => Iterator<U, any, any>

      A function to transform this stream's items.

    Returns Optional<U>

    An Optional containing the first item yielded by the iterator, or empty if no items are yielded.

  • Returns a stream with the element at the specified index replaced by the provided value, while all other elements remain unchanged.

    Negative index counts back from the end of the array, with -1 being the last element, -2 being the second to last, and so on. If the index is out of bounds, a RangeError is thrown.

    Parameters

    • index: number

      The index of the element to replace, converted to an integer.

    • value: T

      The value to insert at the specified index.

    Returns Stream<T>

    A Stream with the element at the specified index replaced by the provided value.

    RangeError - if the index is out of bounds

  • Returns a stream whose elements are pairs, where the first element is an item from this stream and the second element is the corresponding item from the other iterable. The length of the resulting stream is the minimum of this stream's length and the other iterable's length.

    Type Parameters

    • U

    Parameters

    • other: Iterable<U, any, any>

      An iterable to zip with this stream.

    Returns Stream<[T, U]>

    A Stream of [T, U] pairs.

  • Returns a stream composed of n-tuples of consecutive elements from this stream. If n is greater than the number of items in the stream, the resulting stream will be empty.

    Type Parameters

    • N extends number

      The size of each tuple.

    Parameters

    • n: N

      The number of consecutive elements to include in each tuple.

    Returns Stream<TupleOf<T, N>>

    A Stream of n-tuples of consecutive elements.

  • Similar to zip, but requires that this stream and the other iterable have the same length. Throws an error if the lengths do not match.

    Type Parameters

    • U

    Parameters

    • other: Iterable<U, any, any>

      An iterable to zip with this stream.

    Returns Stream<[T, U]>

    A Stream of [T, U] pairs.

  • Returns a stream of pairs where the first element is an item from this stream, and the second element is its index. In other words, it zips with a sequence of integers starting from 0.

    Returns Stream<[T, number]>

    A new Stream of [T, number] pairs.

  • Returns a stream of triplets where the first element is an item from this stream, the second element is its index, and the third element is the size of this stream.

    Returns Stream<[T, number, number]>

    A new Stream of [T, number, number] triplets.

  • Returns a stream of pairs, where each pair contains an item from this stream and the next item. The resulting stream has one less item than the original stream. If the original stream has only one element or is empty, the resulting stream will be empty.

    Returns Stream<[T, T]>

    A Stream of adjacent element pairs.