Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface Stream<T>

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

Stream can be explained as a function over an iterable. Intermediate operations return new functions containing current stream as an input; terminal operations capture input, evaluate functions chain 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 don't store anything except reference to an input. This means streams may be iterated multiple times, and each time the stream is evaluated against input as it was on the moment of invoking terminal operation.

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, map does not copy input data; instead, it retrieves upstream data one by one, and pushes mapped items downstream also value by value. Some operations do require creating intermediate data structures, for example shuffle and sortBy; in this case downstream steps maximize the benefit of having random-access array allowed for modifications.

stream(30, 20, 10, 0)
    .map(i => i + 1) // does not copy data, maps on evaluation
    .sortBy(i => i)  // copies data to the new array and sorts it
    .at(2)           // makes a[2] on array created upstream
    .get()           // => 21

Type parameters

  • T

    Input elements type

Hierarchy

  • Iterable<T>
    • Stream

Index

Methods

[Symbol.iterator]

  • [Symbol.iterator](): Iterator<T>
  • Creates an iterator which yields items of this stream

    Returns Iterator<T>

at

  • Creates an optional which resolves to an element of this stream at index position (negative index counts from last item) if there is such a position, or resolves to empty otherwise.

    Parameters

    • index: number

      Zero-based position to return an item at, or negative position where -1 means last, -2 last-but-one etc.

    Returns Optional<T>

awaitAll

  • awaitAll(): Promise<T extends PromiseLike<infer E> ? E[] : T[]>
  • Calls Promise.all() on this stream and returns the result. If this stream items are Promise<E> returns Promise<E[]>; for more complex cases please refer to MDN documentation.

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

butLast

  • Creates a stream containing all but last items of this stream. The result stream is empty if this stream is empty or contains one item.

    Returns Stream<T>

concat

  • Creates a stream whose items are all items of this stream followed by provided item.

    Parameters

    • item: T

      Item to append

    Returns Stream<T>

concatAll

  • concatAll(items: Iterable<T>): Stream<T>
  • Creates a stream whose items are all items of this stream followed by all items provided by items iterable.

    Parameters

    • items: Iterable<T>

      Items to append to this stream

    Returns Stream<T>

distinctBy

  • distinctBy(getKey: (item: T) => any): Stream<T>
  • Creates a stream containing only elements of this stream for which getKey returns different keys. If multiple items produce the same key, only the first such item is included to the returned stream. Keys are checked using Set which means items are compared mostly in terms of ===; there are exceptions though, see MDN documentation.

    Parameters

    • getKey: (item: T) => any

      Function to get key of items

        • (item: T): any
        • Parameters

          • item: T

          Returns any

    Returns Stream<T>

equals

  • equals(other: Iterable<T>): boolean
  • Returns true if other contains the same number of items and all corresponding items are equal in terms of ===.

    Parameters

    • other: Iterable<T>

      Iterable to test for equality

    Returns boolean

every

  • every(predicate: (item: T) => boolean): boolean
  • Returns true if the predicate returns true for all items of this stream; returns false otherwise. This is short-circuiting operation which means it skips the rest items if the predicate returned false for some item.

    Parameters

    • predicate: (item: T) => boolean

      A function to test each item

        • (item: T): boolean
        • Parameters

          • item: T

          Returns boolean

    Returns boolean

filter

  • filter(predicate: (item: T) => boolean): Stream<T>
  • Creates a stream containing items of this stream which match the provided predicate.

    Parameters

    • predicate: (item: T) => boolean

      The predicate to test items

        • (item: T): boolean
        • Parameters

          • item: T

          Returns boolean

    Returns Stream<T>

filterWithAssertion

  • filterWithAssertion<U>(assertion: (item: T) => item is U): Stream<U>
  • Like filter but allows narrowing output type. For example, if you want to filter out nulls,

    streamOf<string | null>('a', null, 'b')
      .filterWithAssertion(function(item): item is string {
        return typeof item === 'string'
      })
      .toArray()   // => ['a', 'b']: string[]

    Makes sense only for TypeScript code; for JavaScript works exactly the same way as filter.

    Type parameters

    • U: T

    Parameters

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

      The assertion to test items

        • (item: T): item is U
        • Parameters

          • item: T

          Returns item is U

    Returns Stream<U>

find

  • find(predicate: (item: T) => boolean): Optional<T>
  • Creates an optional which resolves to the first item to match predicate, or to empty if no such item found.

    Parameters

    • predicate: (item: T) => boolean

      The predicate to test items

        • (item: T): boolean
        • Parameters

          • item: T

          Returns boolean

    Returns Optional<T>

flatMap

  • flatMap<U>(mapper: (item: T) => Iterable<U>): Stream<U>
  • Creates a stream with the following behavior:

    1. Iterates this stream items
    2. Applies mapper to each item
    3. Chains together at the same level all results returned by mapper

    The operation is also known as chain.

    Type parameters

    • U

    Parameters

    • mapper: (item: T) => Iterable<U>

      The function to transform items

        • (item: T): Iterable<U>
        • Parameters

          • item: T

          Returns Iterable<U>

    Returns Stream<U>

forEach

  • forEach(effect: (item: T) => void): void
  • Invokes effect for each item of this stream

    Parameters

    • effect: (item: T) => void

      An effect to apply to items

        • (item: T): void
        • Parameters

          • item: T

          Returns void

    Returns void

forEachUntil

  • forEachUntil(effect: (item: T) => boolean | undefined | void): boolean
  • Invokes effect for each item of this stream until effect returns true.

    Parameters

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

      An effect to apply to items which also returns stop flag.

        • (item: T): boolean | undefined | void
        • Parameters

          • item: T

          Returns boolean | undefined | void

    Returns boolean

    True if iteration was stopped because some effect returned true, false otherwise.

groupBy

  • groupBy<K>(getKey: (item: T) => K): Stream<[K, T[]]>
  • Creates a stream whose elements are [key, items[]] pairs; keys are retrieved with getKey applied to this stream items; itemss are arrays of this stream items which produced the same key. Order of items is the same as in this stream.

    Type parameters

    • K

    Parameters

    • getKey: (item: T) => K

      Function to get item key with

        • (item: T): K
        • Parameters

          • item: T

          Returns K

    Returns Stream<[K, T[]]>

head

  • Creates an optional which resolves to this stream first item if the stream has item(s), or resolves to empty otherwise.

    Returns Optional<T>

join

  • join(sep?: undefined | string): string
  • join(spec: { leading?: undefined | false | true; sep: string; trailing?: undefined | false | true }): string
  • Concatenates this stream items inserting sep between. Items are mapped to string using String function (without new).

    Parameters

    • Optional sep: undefined | string

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

    Returns string

  • Like join but can insert sep in the beginning and (or) in the end

    Parameters

    • spec: { leading?: undefined | false | true; sep: string; trailing?: undefined | false | true }

      Object specifying separator, and whether to insert it before the first and after the last items

      • Optional leading?: undefined | false | true
      • sep: string
      • Optional trailing?: undefined | false | true

    Returns string

joinBy

  • joinBy(getSep: (l: T, r: T) => string): string
  • Like join but retrieves separator calling getSep for each adjacent items pair.

    Parameters

    • getSep: (l: T, r: T) => string

      A function to get separator for adjacent items pair

        • (l: T, r: T): string
        • Parameters

          • l: T
          • r: T

          Returns string

    Returns string

last

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

    Returns Optional<T>

map

  • map<U>(mapper: (item: T) => U): Stream<U>
  • Creates a stream whose items are all items of this stream transformed by mapper.

    Type parameters

    • U

    Parameters

    • mapper: (item: T) => U

      A function to transform items

        • (item: T): U
        • Parameters

          • item: T

          Returns U

    Returns Stream<U>

peek

  • peek(effect: (item: T) => void): Stream<T>
  • Creates a stream executing an effect for each item and returning the item as is. One possible usage for this method is mutating items in place.

    Parameters

    • effect: (item: T) => void

      The effect to execute

        • (item: T): void
        • Parameters

          • item: T

          Returns void

    Returns Stream<T>

randomItem

  • Creates an optional resolving to a random item of this stream, or resolving to emtpy if this stream is empty.

    Returns Optional<T>

reduce

  • reduce(reducer: (prev: T, curr: T) => T): Optional<T>
  • reduce<U>(reducer: (prev: U, curr: T) => U, initial: U): U
  • Creates 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 first and second items, then applies reducer to previously returned result and third item etc, and resolves to a value returned by the last reducer invocation.

    Parameters

    • reducer: (prev: T, curr: T) => T

      The function to reduce items

        • (prev: T, curr: T): T
        • Parameters

          • prev: T
          • curr: T

          Returns T

    Returns Optional<T>

  • If this stream is empty, returns initial; otherwise applies reducer to initial and the first item, then applies reducer to previously returned result and second item etc, and returns result from last reducer invocation.

    Type parameters

    • U

    Parameters

    • reducer: (prev: U, curr: T) => U

      The function to reduce items

        • (prev: U, curr: T): U
        • Parameters

          • prev: U
          • curr: T

          Returns U

    • initial: U

      Initial value

    Returns U

reduceRight

  • reduceRight(reducer: (prev: T, curr: T) => T): Optional<T>
  • reduceRight<U>(reducer: (prev: U, curr: T) => U, initial: U): U
  • Creates 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 last and 2nd to end items, then applies reducer to previously returned result and 3rd to end item etc, and resolves to a value returned by the last reducer invocation.

    Parameters

    • reducer: (prev: T, curr: T) => T

      The function to reduce items

        • (prev: T, curr: T): T
        • Parameters

          • prev: T
          • curr: T

          Returns T

    Returns Optional<T>

  • If this stream is empty, returns initial; otherwise applies reducer to initial and the last item, then applies reducer to previously returned result and 2nd to end item etc, and returns result from last reducer invocation.

    Type parameters

    • U

    Parameters

    • reducer: (prev: U, curr: T) => U

      The function to reduce items

        • (prev: U, curr: T): U
        • Parameters

          • prev: U
          • curr: T

          Returns U

    • initial: U

      Initial value

    Returns U

reverse

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

    Returns Stream<T>

shuffle

  • Creates a stream whose elements are elements of this stream with random order.

    Returns Stream<T>

single

  • Creates an optional which resolves to an item if this stream contains only one item, or which resolves to empty otherwise.

    Returns Optional<T>

size

  • size(): number
  • Returns the number of items in this stream

    Returns number

some

  • some(predicate: (item: T) => boolean): boolean
  • Returns true if the predicate returns true for any item of this stream; returns false otherwise. This is short-circuiting operation which means it skips the rest items if the predicate returned true for some item.

    Parameters

    • predicate: (item: T) => boolean

      A function to test each item

        • (item: T): boolean
        • Parameters

          • item: T

          Returns boolean

    Returns boolean

sort

  • sort(compareFn?: undefined | ((a: T, b: T) => number)): Stream<T>
  • Creates a stream whose items are sorted items of this stream. The implementation relies on Array.sort().

    Parameters

    • Optional compareFn: undefined | ((a: T, b: T) => number)

      Comparison function with semantics described in MDN

    Returns Stream<T>

sortBy

  • sortBy(getComparable: (item: T) => number | string | boolean): Stream<T>
  • Creates a stream with items of this stream ordered by value returned by getComparable. Returned values are compared with > and <.

    Parameters

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

      A function which, given an item, returns comparable value. Returned value of the function is not cached, so it's recommended to not to perform heavy computations.

        • (item: T): number | string | boolean
        • Parameters

          • item: T

          Returns number | string | boolean

    Returns Stream<T>

splitWhen

  • splitWhen(isSplit: (l: T, r: T) => boolean): Stream<T[]>
  • Creates a stream whose items are groups of this stream adjacent items for which isSplit returned false; in other words, given all items as a sequence, splits it between items for which isSplit returns true. Order of items in arrays is the same as it is in this stream.

    Parameters

    • isSplit: (l: T, r: T) => boolean

      A function to check if items sequence should be split between l and r items

        • (l: T, r: T): boolean
        • Parameters

          • l: T
          • r: T

          Returns boolean

    Returns Stream<T[]>

tail

  • Creates a stream which contains all but first item of this stream. If this stream is empty or contains one item the returned stream is empty.

    Returns Stream<T>

take

  • Creates a stream containing no more than n first items of this stream

    Parameters

    • n: number

      Max leading items to select from this stream

    Returns Stream<T>

takeLast

  • takeLast(n: number): Stream<T>
  • Creates a stream containing no more than n last items of this stream

    Parameters

    • n: number

      Max trailing items to select from this stream

    Returns Stream<T>

takeRandom

  • takeRandom(n: number): Stream<T>
  • Creates a stream containing no more than n random items of this stream. The result is sampled without replacement i.e. one item of this stream appears in the result stream no more than once.

    Parameters

    • n: number

      Max items to sample

    Returns Stream<T>

toArray

  • toArray(): T[]
  • Returns stream items as an array

    Returns T[]

toObject

  • toObject(): T extends readonly [string | number | symbol, any] ? {} : unknown
  • If elements of this stream are [key, value] pairs where key is string, number, or symbol, collects stream items to an object; if some key appears multiple times in this stream, only the last [key, value] will be included in the result object. If elements of this stream are not [key, value] as described above throws an error.

    Using in TypeScript may require putting as const after each tuple to help TS infer 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] ? {} : unknown

transform

  • transform<U>(operator: (input: Iterable<T>) => Iterator<U>): Stream<U>
  • Extension method to apply arbitrary operator to the stream. An operator is passed an iterable which yields this stream items, and it must return the iterator which is an input for the next step. The easiest way is to use 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>) => Iterator<U>

      A function which is passed an iterable yielding this stream items, and which is expected to return iterator for downstream step

        • (input: Iterable<T>): Iterator<U>
        • Parameters

          • input: Iterable<T>

          Returns Iterator<U>

    Returns Stream<U>

transformToOptional

  • transformToOptional<U>(operator: (input: Iterable<T>) => Iterator<U>): Optional<U>
  • Like transform but returns optional which discards all but first item yielded by an iterator returned by an operator.

    Type parameters

    • U

    Parameters

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

      A function to transform this stream items

        • (input: Iterable<T>): Iterator<U>
        • Parameters

          • input: Iterable<T>

          Returns Iterator<U>

    Returns Optional<U>

zip

  • zip<U>(other: Iterable<U>): Stream<[T, U]>
  • Creates a stream whose elements are pairs where the first element is this stream item and the second element is the corresponding item of the other iterable. The length of the result stream is the minimum of this stream length and other length.

    Type parameters

    • U

    Parameters

    • other: Iterable<U>

      An iterable to zip this stream with

    Returns Stream<[T, U]>

zipStrict

  • zipStrict<U>(other: Iterable<U>): Stream<[T, U]>
  • Like zip but requires that this stream and other iterable have the same length, otherwise throws an error.

    Type parameters

    • U

    Parameters

    • other: Iterable<U>

      An iterable to zip this stream with

    Returns Stream<[T, U]>

zipWithIndex

  • zipWithIndex(): Stream<[T, number]>
  • Creates a stream of pairs where first element is this stream item, and the second one is its index. In other words, zips with integers sequence starting with 0.

    Returns Stream<[T, number]>

zipWithIndexAndLen

  • zipWithIndexAndLen(): Stream<[T, number, number]>
  • Creates s stream of triplets where the first element is this stream item, second element is its index, and third one is this stream size.

    Returns Stream<[T, number, number]>

Generated using TypeDoc