Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface IStream<T>

A stream represents a sequence of values. Use a factory method for creating streams either from iterables or other objects:

const myStream = require("streams").stream([1,2,3])
const yourStream = require("streams").times(10) // Stream[0,1,2,3,...,9]

Streams may be transformed into other stream via non-terminal methods such as IStream#map or IStream#filter:

stream([1,2,3]).map(x => x * x) // => Stream[2,4,6]
stream("foobar").filter(x => x > "c") // => Stream["f", "o", "o", "r"]

Streams do not process their items until a terminal operation is applied to the stream:

// Does not print anything as visit is not a terminal operation.
stream("foobar").visit(console.log).filter(x => x > "a")
// End is a terminal operation that causes the stream to be processed.
stream("foobar").visit(console.log).filter(x => x > "a").end()

After a terminal or non-terminal operation was applied, no other operation may be applied to the original stream anymore:

const myStream = stream([9,10,11])
myStream.forEach(console.log) // prints 9,10,11
myStream.forEach(console.log) // throws an Error: Stream was already consumed.

Type parameters

  • T

    Type of the items in the stream.

Hierarchy

Implemented by

Index

Methods

__@iterator

  • __@iterator(): Iterator<T>
  • Returns Iterator<T>

chunk

  • chunk(chunkSize: 0): IStream<never>
  • chunk(chunkSize: 1): IStream<Single<T>>
  • chunk(chunkSize: 2): IStream<Pair<T> | Single<T>>
  • chunk(chunkSize: 3): IStream<Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 4): IStream<Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 5): IStream<Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 6): IStream<Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 7): IStream<Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 8): IStream<Octuple<T> | Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 9): IStream<Nonuple<T> | Octuple<T> | Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: 10): IStream<Decuple<T> | Nonuple<T> | Octuple<T> | Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>
  • chunk(chunkSize: number): IStream<T[]>
  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 0

    Returns IStream<never>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 1

    Returns IStream<Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 2

    Returns IStream<Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 3

    Returns IStream<Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 4

    Returns IStream<Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 5

    Returns IStream<Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 6

    Returns IStream<Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 7

    Returns IStream<Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 8

    Returns IStream<Octuple<T> | Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 9

    Returns IStream<Nonuple<T> | Octuple<T> | Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>

    Parameters

    • chunkSize: 10

    Returns IStream<Decuple<T> | Nonuple<T> | Octuple<T> | Septuple<T> | Sextuple<T> | Quintuple<T> | Quadruple<T> | Triple<T> | Pair<T> | Single<T>>

  • Chunks the items into chunks of chunkSize.

    stream([1,2,3,4,5]).chunk(2) // => Stream[ [1,2], [3,4], [5] ]
    stream([1,2,3,4,5]).chunk(1) // => Stream[ [1], [2], [3], [4], [5] ]
    stream([1,2,3,4,5]).chunk(0) // => Stream[]
    stream([1,2,3,4,5]).chunk(NaN) // => Stream[]
    stream([1,2,3,4,5]).chunk(Infinity) // => Stream[[1,2,3,4,5]]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • chunkSize: number

      Size of the produced chunks.

    Returns IStream<T[]>

    A stream over the chunked items.

chunkBy

  • chunkBy<K>(classifier: TypedBiFunction<T, number, K>): IStream<T[]>
  • Chunks together consecutive items for which the classifier returns the same value. Equality is checked with ===.

    stream([1,2,3,4,5,6,1]).chunkBy(i => i & 10)
    // => Stream[ [1,2], [3,4], [5,6], [1] ]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

      Type of the returned value of the chunker,

    Parameters

    • classifier: TypedBiFunction<T, number, K>

      It is passed the item as its first argument and the index as its second. Items are chunked together according to the returned value.

    Returns IStream<T[]>

    A stream over the chunked items.

collect

  • collect<S, R>(collector: Collector<T, S, R>): R
  • Creates an object and incorporates all items into that object.

    stream([1,2,3]).collect(Collectors.summarize)
    // => Statistic[min:1, max:3, count: 3, sum: 6, average: 2, variance: 0.67]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the intermediate object that incorporates each item in order.

    • R

      Type of the final collected value.

    Parameters

    • collector: Collector<T, S, R>

      How to collect the items.

    Returns R

    The collected value.

collectWith

  • collectWith<S, R>(supplier: Supplier<S>, accumulator: BiConsumer<S, T>, finisher: TypedFunction<S, R>): R
  • Same as {@link #collect}, but allows specifying the parts of the collector individually.

    stream([1,2,3]).collect(() => [], (array, x) => array.push(x), x => new Set(x))
    // => Set[1,2,3]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the intermediate value that incorporates each item in order.

    • R

      Type of the final collected value.

    Parameters

    • supplier: Supplier<S>
    • accumulator: BiConsumer<S, T>

      Takes the intermediate objects as its first argument and the current items as its seconds, and incorporates the item into the intermediate value.

    • finisher: TypedFunction<S, R>

      Takes the intermediate object with all the items incoporated, and transforms it into the final value.

    Returns R

    The final collected value.

concat

  • concat(...iterables: Iterable<T>[]): this
  • Concatenates all given iterables with this stream into one stream of all the items.

    stream("foo").concat("bar", "baz")
    // => Stream["f", "o", "o", "b", "a", "r", "b", "a", "z"]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Rest ...iterables: Iterable<T>[]

    Returns this

    A stream over all the items of this stream and the given iterables.

consume

  • consume(sink: T[] | Consumer<T>, offset?: undefined | number, maxAmount?: undefined | number): this
  • Consumes the given amount of items at a given offset from the start of of this stream, and adds thems to the sink. The items at the start of the stream and the remaining items can be read from the returned stream.

    const sink = [];
    const s = stream("foobar").consume(sink, 0, 3);
    // => sink is now ["f", "o", "o"]
    s.join() // => "bar"
    
    const sink2 = [];
    const s2 = stream("foobar").consume(sink, 2, 3);
    // => sink is now ["o", "b", "a"]
    s2.join() // => "for"
    
    stream("foobar").consume(console.log, 0, 3);
    // => logs "f", "o", "o"
    
    stream("foobar").consume(console.log, 0, -3);
    // => logs nothing
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams; unless parameter offset or maxAmount is set to `Infinity.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • sink: T[] | Consumer<T>

      If an array, consmed items are added to the array. Otherwise, the consumer is called with the consumed item.

    • Optional offset: undefined | number

      Where to start consuming items. Defaults to 0.

    • Optional maxAmount: undefined | number

      Maximum number of items to consume. Defaults to Infinity.

    Returns this

    A stream over the remaining items.

cycle

  • cycle(count?: undefined | number): this
  • Cycles over the elements of this stream the given number of times.

    stream([1,2,3]).cycle(NaN) // => Stream[]
    stream([1,2,3]).cycle(0) // => Stream[]
    stream([1,2,3]).cycle(3) // => Stream[1,2,3,1,2,3,1,2,3]
    stream([1,2,3]).cycle().limit(5) // => Stream[1,2,3,1,2]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional count: undefined | number

      The number of cycle. If not given, cycles the items endlessly.

    Returns this

    A stream with the items of the this stream repeating.

end

  • end(): void
  • Applies all pending operations, ending this stream.

    stream([1,2,3]).visit(console.log) // Stream[1,2,3]; prints nothing
    stream([1,2,3]).visit(console.log).end() // prints 1,2,3
    

    Note that for the above example, you could also simply use forEach.

    stream([1,2,3]).forEach(console.log) // prints 1,2,3
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns void

every

  • every(predicate: Predicate<T>): boolean
  • Determines whether every items matches the given predicate.

    stream("fooz").every(x => x < "j") // => false
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams; unless an item is encountered that does not match the predicate.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • predicate: Predicate<T>

      Test to be performed on the items.

    Returns boolean

    Whether every items matches the given predicate.

filter

  • filter(predicate: Predicate<T>): this
  • Removes all elements from this stream for which the predicate does not return true.

    stream([4,-4,2,-9]).filter(x => x > 0) // => Stream[4,2]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • predicate: Predicate<T>

      Testing function returning true iff the item is to be kept, false otherwise.

    Returns this

    A stream over all items for which the predicate returned true.

filterBy

  • filterBy<K>(target: K, keyExtractor: TypedFunction<T, K>, comparator?: Comparator<K>): this
  • Similar to IStream#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.

    stream(["foo", "bar", "foobar"]).filterBy(x => x.length)
    // => Stream["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}}
    
    stream([user1, user2, user3]).filterBy(2005, user => user.birth, (lhs,rhs) => lhs.year - rhs.year)
    // => Stream[user1, user2]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

    Parameters

    • target: K

      Target for filterting. All items in the stream not equivalent to the target are removed.

    • keyExtractor: TypedFunction<T, K>

      Extracts the key by which equality is determined. Default to identity x => x.

    • Optional comparator: Comparator<K>

      Comparator for comparing two keys. Defaults to the natural comparator using < and >.

    Returns this

    A stream over all items whose keys compare equal to the given target.

find

  • find(predicate: BiPredicate<T, number>): Maybe<T>
  • Searches for the first occurence of an item matching the predicate.

    stream(["foo1", "bar,"foo2").find(x => x.startsWith("foo")) // => "foo1"
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams; unless an item is encountered that matches the predicate.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • predicate: BiPredicate<T, number>

      Test to be performed on the items. It is passed the current item and the current index.

    Returns Maybe<T>

    The item iff found, undefined otherwise.

findIndex

  • findIndex(predicate: BiPredicate<T, number>): number
  • Searches for the first occurence of an item matching the predicate, and returns the index, or -1 otherwise.

    stream(["foo1", "bar, "foo2").find(x => x.startsWith("foo")) // => 0
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams; unless an item is encountered that matches the predicate.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • predicate: BiPredicate<T, number>

      Test to be performed on the items. It is passed the current item and the current index.

    Returns number

    The index iff the item was found, -1 otherwise.

first

  • first(): Maybe<T>
  • Returns the first item and closes the stream.

    stream("foo").first() // => "f"
    stream("").first() // => undefined
    
    const s = stream("foobar");
    s.first()
    s.first() // => Error
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns Maybe<T>

    The item at the first position, or undefined if empty.

flatMap

  • flatMap<S>(mapper: TypedFunction<T, Iterable<S>>): IStream<S>
  • Applies the mapping function to each item and return a stream over all the mapped iterables. This is equivalent to concat(map(mapper))`.

    stream(["foo","bar"]).flatMap(x => x)
    // => Stream["f", "o", "o", "b", "a", "r"]
    
    stream(["[1]","[2,3]","[4,]"]).try(JSON.parse).flatMap(x=>x.stream())
    // => Stream[ [1], [2, 3] ]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the elements in the produced stream.

    Parameters

    • mapper: TypedFunction<T, Iterable<S>>

      Mapping function taking each item and producing a new stream or iterable.

    Returns IStream<S>

    A stream over all the items of the iterables produced by the mapper.

forEach

  • forEach(consumer: Consumer<T>): void
  • Passes each item of this stream to the given consumer.

    stream([1,2,3]).forEach(console.log); // prints 1,2,3
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • consumer: Consumer<T>

      A callback that receives each item of this stream in order.

    Returns void

fork

  • fork(): this
  • This returns a stream that leaves the original stream open and iterable. If the underlying iterable is an array, set, map or string etc, it simpy reuses that iterable, otherwise it buffers the items temporarily.

    function * foo() {
      return 1;
      return 2;
      return 3;
    }
    
    const transientStream = stream(foo());
    transientStream.toArray() // => [1,2,3]
    transientStream.toArray() // => Error: Stream was consumed already.
    
    const persistentStream = stream(foo())
    persistentStream.fork().toArray() // => [1,2,3]
    persistentStream.fork().toArray() // => [1,2,3]
    persistentStream.toArray()        // => [1,2,3]
    persistentStream.fork()           // => Error: Stream was consumed already.
    

    Note that buffering takes place on-demand, so the following will not enter an infinite loop:

    // Create a stream with an unlimited amount of items.
    const stream = TypesafeStreamFactory.generate(Math.random, Infinity);
    
    // Fork the stream first, then limit to a finite number of items.
    // Items already produced are not recomputed.
    stream.fork().limit(3).toArray() // => [0.28, 0.14, 0.97]
    stream.fork().limit(2).toArray() // => [0.28, 0.14]
    stream.fork().limit(4).toArray() // => [0.28, 0.14, 0.97, 0.31]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    non_terminal

    This is a non-terminal operation. The original stream object can still be used.

    Returns this

    A forked stream that leaves the original stream usable.

group

  • group<K>(classifier: TypedFunction<T, K>): Map<K, T[]>
  • Splits the items into several groups, according to the given classifier.

    stream(["a", "foo", "is", "some", "buzz"]).group(x => x.length) // => Map [ 1 => ["a"], 2 => ["is"], 3 => "is", 4 => ["some", "buzz"] ]
    
    typearam

    K Type of the group key.

    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

    Parameters

    • classifier: TypedFunction<T, K>

      Returns the group for each item.

    Returns Map<K, T[]>

    A map with the groups as keys and arrays as values, containing all the items for that group.

has

  • has(object: T): boolean
  • Determines whether this stream contains the given item. Equivalence is checked with ===. This is equivalent to `stream(...).some(x => x === object)`.

    stream("foobar").has("o") // => true
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams; unless the item is encountered.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • object: T

    Returns boolean

    Whether the given object is contained in this stream.

index

  • Adds the index to each element of this stream. The index starts at 0.

    stream(["foo", "bar"]).index().toMap(({value}) => value, ({index}) => index})
    // => Map<"foo" => 0, "bar" => 1>
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns IStream<object>

    A stream with each item being an array consisting of the item's index and the item itself. The index starts at 0.

isEmpty

  • isEmpty(): boolean
  • Determines whether this stream contains no items. This consumes at most one item from the stream and works with infinite streams.

    This method leaves the original stream intact, ie. you can call other methods on the original stream and get the same result as if this methods had not been called.

    stream([]).isEmpty()      // => true
    stream([1,2,3]).isEmpty() // => false
    
    const s = stream([1,2,3]);
    if (!s.isEmpty()) {
      // This works and includes all three items because
      // isEmpty left the stream intact.
      s.map(x=>x*x).toArray() // => [2,4,6]
    }
    
    see

    IStream#isSizeBetween

    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    non_terminal

    This is a non-terminal operation. The original stream object can still be used.

    Returns boolean

    True iff this stream contains no items.

isSizeBetween

  • isSizeBetween(lower?: undefined | number, upper?: undefined | number): boolean
  • Determines whether the number of items in this stream is at least lower and at most upper. This method only consumes as many elements from the stream as necessary and may be used with infinite stream. Using stream.size() === 0 would force an endless iteration of all its item.

    This method leaves the original stream intact, ie. you can call other methods on the original stream and get the same result as if this methods had not been called.

    stream([1,2,3]).isSizeBetween(0, 3) // => true
    stream([1,2,3]).isSizeBetween(1, 3) // => true
    stream([1,2,3]).isSizeBetween(3, 3) // => true
    stream([1,2,3]).isSizeBetween(3, 4) // => true
    stream([1,2,3]).isSizeBetween(2, Infinity) // => true
    stream([1,2,3]).isSizeBetween(-4, 2) // => false
    stream([1,2,3]).isSizeBetween(4, 9) // => false
    stream([1,2,3]).isSizeBetween(1, 2) // => false
    
    stream([1,2,3]).isSizeBetween(0) // => true
    stream([1,2,3]).isSizeBetween(1) // => true
    stream([1,2,3]).isSizeBetween(3) // => true
    stream([1,2,3]).isSizeBetween(4) // => false
    
    stream([]).isSizeBetween(0, 0) // => true
    stream([]).isSizeBetween(1, 3) // => false
    
    stream([]).isSizeBetween()      // => true
    stream([1,2,3]).isSizeBetween() // => true
    
    stream([]).isSizeBetween(NaN)           // => false
    stream([1,2,3]).isSizeBetween(NaN)      // => false
    stream([]).isSizeBetween(NaN, NaN)      // => false
    stream([1,2,3]).isSizeBetween(NaN, NaN) // => false
    
    see

    IStream#isEmpty

    infinite_stream

    Does not hang when used on infinite (unlimited) streams; unless argument lower is set to Infinity.

    non_terminal

    This is a non-terminal operation. The original stream object can still be used.

    Parameters

    • Optional lower: undefined | number

      Minimum number of items allowed. Defaults to 0.

    • Optional upper: undefined | number

      Maximum number of items allowed. Defaults to Infinity.

    Returns boolean

    True iff this stream contains the specified number of items.

join

  • join(delimiter?: undefined | string, prefix?: undefined | string, suffix?: undefined | string): string
  • Joins every time with the given delimiter, optionally prepending a prefix and appending a suffix to the output.

    stream([1,2,3]).join(",", "[", "]") // => "[1,2,3]"
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional delimiter: undefined | string

      String inserted between the items. Defaults to the empty string.

    • Optional prefix: undefined | string

      String prepended to the joined string. Defaults to the empty string.

    • Optional suffix: undefined | string

      String appended to the joined string. Defaults to the empty string.

    Returns string

    A string consisting of the prefix, the items joined with the delimiter, and the suffix.

last

  • last(): Maybe<T>
  • Returns the last item.

    stream("foo").last() // => "o"
    stream("").last() // => undefined
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns Maybe<T>

    The item at the last position, or undefined if empty.

limit

  • limit(limitTo?: undefined | number): this
  • Limits the stream to at most the given number of elements.

     stream([1,2,3,4,5,6]).limit(NaN) // => Stream[1,2,3,4,5,6]
     stream([1,2,3,4,5,6]).limit(0) // => Stream[1,2,3,4,5,6]
     stream([1,2,3,4,5,6]).limit(3) // => Stream[1,2,3]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional limitTo: undefined | number

    Returns this

    A stream with at most the given number of items.

map

  • map<S>(mapper: TypedFunction<T, S>): IStream<S>
  • Transform each element to another element of a possibly different type.

    stream([0,1,2,3]).map(x => 2 * x) // => Stream[0,2,4,6]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the elements in the produced stream.

    Parameters

    • mapper: TypedFunction<T, S>

      A function taking each item of this stream and transforms it into another item.

    Returns IStream<S>

    A stream over the mapped elements.

max

  • max(comparator?: Comparator<T>): Maybe<T>
  • Computes the maxmimum of the items.

    stream([6,2,3,9,4]).max() // => 9
    stream(["foo", "bar", "I"]).max(Comparators.byField("length")) // => "foo"
    stream([]).max() // => undefined
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional comparator: Comparator<T>

      How two items are compared. Defaults to the natural order, ie. by using &lt; and &gt;.

    Returns Maybe<T>

    The largest item. If there are multiple largest items, returns the first. undefined iff this stream is empty.

maxBy

  • maxBy<K>(sortKey: TypedFunction<T, K>): Maybe<T>
  • Computes the maximum of the items, as determined by the given sort key.

    stream(["foo","foobar", "gg"]).maxBy(x => x.length)
    // => "gg"
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

    Parameters

    • sortKey: TypedFunction<T, K>

      Takes an item and produces the key by which the maximum is determined.

    Returns Maybe<T>

    The smallest item, or undefined iff there are no items.

min

  • min(comparator?: Comparator<T>): Maybe<T>
  • Computes the minimum of the items.

    stream([3,2,9,4]).min() // => 9
    stream(["foo", "bar", "I"].min(Comparators.byField("length")) // => "I"
    stream([]).min() // => undefined
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional comparator: Comparator<T>

      How two items are compared. Defaults to the natural order, ie. by using &lt; and &gt;.

    Returns Maybe<T>

    The smallest item. If there are multiple smallest items, returns the first. undefined iff this stream is empty.

minBy

  • minBy<K>(sortKey: TypedFunction<T, K>): Maybe<T>
  • Computes the minimum of the items, as determined by the given sort key.

    stream(["foo","foobar", "gg"]).minBy(x => x.length)
    // => "gg"
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

    Parameters

    • sortKey: TypedFunction<T, K>

      Takes an item and produces the key by which the minimum is determined.

    Returns Maybe<T>

    The smallest item, or undefined iff there are no items.

none

  • none(predicate: Predicate<T>): boolean
  • Determines whether no item matches the given predicate. This is equivalent to !stream.some(predicate).

    stream("fooz").none(x => x === "o") // => false
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams; unless an item matches the predicate.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • predicate: Predicate<T>

      Test to be performed on each item.

    Returns boolean

    Whether no item matches the given predicate.

nth

  • nth(n: number): Maybe<T>
  • Returns the items at the n-th position.

    stream("foo").nth(1) // => "f"
    
    stream("foo").nth(3) // => undefined
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams; unless argument n is set to Infinity.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • n: number

      The position of the item to get.

    Returns Maybe<T>

    The item at the given position, or undefined if not found.

partition

  • partition(discriminator: Predicate<T>): object
  • Splits the items into two groups according to the given discriminator.

    stream([-3,2,9,-4]).partition(x => x > 0) // => { false: [-3,-4], true: [2,9]}
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • discriminator: Predicate<T>

      Partitions each item into one of two groups by returning true of false.

    Returns object

    An object containing the partitioned items.

    • false: T[]
    • true: T[]

promise

  • promise<S>(promiseConverter: TypedFunction<T, Promise<S>>): Promise<IStream<S>>
  • Converts each item to a promise and returns a promise that is resolved with a stream of results when all of the created Promises resolve, or rejected when any Promise is rejected.

    stream([1,2,3])
      .promise(id => fetch(`/user/${id}`))
      .then(s => s.forEach(renderUser))
      .catch(console.error)
    // Calls the renderUser method with the Response for each user request.
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the item of the promises.

    Parameters

    • promiseConverter: TypedFunction<T, Promise<S>>

      Takes each item and creates a promise.

    Returns Promise<IStream<S>>

    A promise that resolves when all promises resolve; or is rejected when any promise is rejected.

reduce

  • reduce<S>(reducer: TypedBiFunction<S, T, S>, initialValue: S): S
  • Coalesces all items into one value.

    stream([1,2,3]).reduce((sum,x) => sum + x, 10) // => 16
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the reduced value.

    Parameters

    • reducer: TypedBiFunction<S, T, S>

      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.

    • initialValue: S

      The initial value of the reduction.

    Returns S

    The reduced value, or the initial value iff this stream is empty.

reduceSame

  • reduceSame(reducer: TypedBiFunction<T, T, T>): Maybe<T>
  • Similar to reduceSame, but reduces to items of the same type as the items and thus does not require an explicit initial value.

    stream([1,2,3]).reduceSame((sum,x) => sum + x) // => 6
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • reducer: TypedBiFunction<T, T, T>

      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.

    Returns Maybe<T>

    The reduced value, or undefined iff the stream is empty.

reverse

  • reverse(): this
  • Reverses the order of the items.

    Note that the items need to be saved temporarily, so that this does not work with unlimited streams, as the last item needs to be accesed first.

    This method might create a new array, but if it does, calling toArray on the returned stream will return that array instead of allocating a new array.

    stream([1,2,3]).reverse() // => Stream[3,2,1]
    stream(factory.step(Infinity)).reverse() // hangs
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns this

    A stream with the items in reversed order.

shift

  • shift(): Maybe<T>
  • Returns the first item and keeps the stream open. The remaining items can still be read from the stream.

    stream("foo").shift() // => "f"
    stream("").shift() // => undefined
    
    const s = stream("foobar");
    s.shift() // => "f"
    s.shift() // => "o"
    s.shift() // => "o"
    s.join() // => "bar"
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns Maybe<T>

    The item at the first position, or undefined if empty.

size

  • size(): number
  • Counts the items.

    stream([1,2,3]).count() // => 3
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns number

    The number of items in this stream.

skip

  • skip(toSkip?: undefined | number): this
  • Discards the given number of items from this stream.

    stream([1,2,3,4,5,6]).skip(3) // => Stream[4,5,6]
    
    see

    limit

    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional toSkip: undefined | number

      How many items to skip. Default to Infinity.

    Returns this

    A stream with the given number of items skipped.

slice

  • slice(startOffset?: undefined | number, endOffset?: undefined | number): T[]
  • Returns the items from the startOffset up to, but not including, the endOffset. This leaves the stream unchanged, all items are still available for further chaining.

    const s = stream("foobar");
    s.slice(0, 3); // => ["f", "o", "o"]
    s.join() // => "foobar"
    
    const s2 = stream("foobar");
    s.slice(2, 5); // => ["o", "b", "a"]
    s.join() // => "forbar"
    
    // special cases
    stream("foo").slice(0, 0)        // => []
    stream("foo").slice(3, 2)        // => []
    stream("foo").slice(0, 2.5)      // => ["f", "o"]
    stream("foo").slice(0.5, 2)      // => ["f", "o"]
    stream("foo").slice(-5, 2)       // => ["f", "o"]
    stream("foo").slice(0, Infinity) // => ["f", "o", "o"]
    stream("foo").slice(Infinity, 9) // => []
    stream("foo").slice(0, NaN)      // => []
    stream("foo").slice(NaN, 2)      // => []
    stream("foo").slice(NaN, NaN)    // => []
    factory.generate(Math.random).slice(Infinity, Infinity) // => []
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams; unless argument startOffset or endOffset is set to Infinity.

    non_terminal

    This is a non-terminal operation. The original stream object can still be used.

    Parameters

    • Optional startOffset: undefined | number

      Position (inclusive) at which to start removing items from this stream. Default to 0.

    • Optional endOffset: undefined | number

      Position (not inclusive) at which to stop removing items from this stream. Defaults to Infinity.

    Returns T[]

    The items in this stream from startOffset up to, but not including, endOffset.

some

  • some(predicate: Predicate<T>): boolean
  • Determines whether at least one items matches the given predicate.

    stream("fooz").some(x => x < "j") // => true
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams; unless an item matches the predicate.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • predicate: Predicate<T>

      Test to be performed on the items.

    Returns boolean

    Whether some (at least one) item matches the given predicate.

sort

  • sort(comparator?: Comparator<T>): this
  • Sorts the items according to the given comparator.

    This method might create a new array, but if it does, calling toArray on the returned stream will return that array instead of allocating a new array.

    stream(["foobar", "a", "bar").sor(Comparators.byField("length")]
    // => Stream["a", "bar", "foobar"]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional comparator: Comparator<T>

      How to sort the items. Default to the natural order, ie. by using &lt; and &gt;.

    Returns this

    A stream with the items in sorted order.

sortBy

  • sortBy<K>(keyExtractor: TypedFunction<T, K>, comparator?: Comparator<K>): this
  • Similar to IStream#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 on the returned stream will return that array instead of allocating a new array.

    stream(["foo", "foobar", "bar"]).sortBy(x => x.length)
    // => Stream["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}}
    
    stream([user1, user2, user3]).filterBy(user => user.birth, (lhs,rhs) => lhs.year - rhs.year)
    // => Stream[user1, user3, user1]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

    Parameters

    • keyExtractor: TypedFunction<T, K>

      Extracts the key by which the sort order is determined. Default to identity x => x.

    • Optional comparator: Comparator<K>

      Comparator for comparing two keys. Defaults to the natural comparator using < and >.

    Returns this

splice

  • splice(offset?: undefined | number, maxAmount?: undefined | number): T[]
  • Extracts (removes) and returns at most maxAmount items of this stream, starting at the given start position. All items up to the starting point and the remaining items are left in this stream and can still be read from it.

    const s = stream("foobar");
    s.splice(0, 3); // => ["f", "o", "o"]
    s.join() // => "bar"
    
    const s2 = stream("foobar");
    s.splice(2,3); // => ["o", "b", "a"]
    s.join() // => "for"
    
    // special cases
    stream("foo").splice(0, 0)        // => []
    stream("foo").splice(0, Infinity) // => ["f", "o", "o"]
    stream("foo").splice(Infinity, 9) // => []
    stream("foo").splice(0, NaN)      // => []
    stream("foo").splice(NaN, 2)      // => []
    stream("foo").splice(NaN, NaN)    // => []
    factory.generate(Math.random).splice(Infinity, 0) // => []
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams; unless argument offset or maxAmount is set to Infinity.

    non_terminal

    This is a non-terminal operation. The original stream object can still be used.

    Parameters

    • Optional offset: undefined | number

      Position at which to start removing items from the stream. Default to 0.

    • Optional maxAmount: undefined | number

      Maximum number if items to read from this stream. Defaults to Infinity.

    Returns T[]

    At most maxAmount items from the given start position of this stream.

sum

  • sum(converter?: TypedFunction<T, number>): number
  • Sums all items arithmetically. If there are no items in the stream, returns NaN.

    stream([]).sum() // => NaN
    stream([1,2,3]).sum() // => 6
    stream(["I", "of", "Borg"]).sum(x => x.length) // => 7
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional converter: TypedFunction<T, number>

    Returns number

    The sum of the items.

toArray

  • toArray(fresh?: undefined | true | false): T[]
  • Creates an array with the items of this stream. If the underlying iterable is an array, returns that array instead of creating a new array.

    stream("foobar").toArray()
    // => ["f", "o", "o", "b", "a", "r"]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional fresh: undefined | true | false

      Iff true, always creates a new array. Otherise, reuses existing array when possible.

    Returns T[]

    An array with the items.

toJSON

  • toJSON(): T[]
  • Hook for JSON.stringify. Returns the items of this stream as an array. Note that this terminates the stream, any subsequent operations on the stream will fail.

    stream("foo").toJSON()
    // => ["f", "o", "o"]
    
    JSON.stringify(stream("foo"))
    // => '["f","o","o"]'
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns T[]

    An array with the items of this stream, in the order they are encountered.

toMap

  • toMap<K, V>(keyMapper: TypedFunction<T, K>, valueMapper: TypedFunction<T, V>, merger?: BinaryOperator<V>): Map<K, V>
  • Creates a map from the items of this stream. 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.

    stream(["foo", "bar"]).toMap(x => x, x => x.length)
    // => Map[ "foo" => 3, "bar" => 3 ]
    
    const data = [{id: 0, name: "foo"}, {id: 0, name: "bar"}];
    
    stream(data).toMap(x => x.id, x => x.name)
    // => Map[ 0 => "bar" ]
    
    stream(data).toMap(x => x.id, x => x.name, (name1, name2) => name1 + "," + name2)
    // => Map[ 0 => "foo,bar" ]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

      Type of the map's keys.

    • V

      Type of the map's values.

    Parameters

    • keyMapper: TypedFunction<T, K>

      Transforms an item into the map key to be used.

    • valueMapper: TypedFunction<T, V>

      Transforms an item into the value used for the corresponding key.

    • Optional merger: BinaryOperator<V>

      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.

    Returns Map<K, V>

    A map with all the mapped key-value-pairs of the items.

toSet

  • toSet(fresh?: undefined | true | false): Set<T>
  • Creates a set with the items of this stream. If the underlying iterable is a set, returns that set instead of creating a new set.

    stream("foobar").toSet()
    // => Set["f", "o", "b", "a", "r"]
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional fresh: undefined | true | false

      Iff true, always creates a new set. Otherwise, reuses existing set when possible.

    Returns Set<T>

    A set with the items.

try

  • try<S>(operation: TypedFunction<T, S>): ITryStream<S>
  • Maps each item to the result of the given operation, wrapped in a ITry for error handling.

    stream(["1","7","7a"])
      .try(SON.parse)
      .discardError(console.error)
      .toArray();
    // => ["success", "success", "error"]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the result of the operation.

    Parameters

    • operation: TypedFunction<T, S>

      Takes each item and returns a mapped value, or throws an Error.

    Returns ITryStream<S>

    A stream with the mapped values and additional methods for handling errors.

tryCompute

  • tryCompute<S>(operation: TypedFunction<IStream<T>, S>): ITry<S>
  • Passes this stream to the the operation and returns its result, wrapped in a ITry in case the operation throws an error. Usually used for performing a terminal operation with error handling on the stream.

    stream([1,2,3]).tryCompute(s => s.sum(item => {throw new Error()}))
    // => Try[success=false]
    
    infinite_stream

    Whether it hangs when used on infinite (unlimited) streams depends on the given operation.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

      Type of the value produced by the operation.

    Parameters

    • operation: TypedFunction<IStream<T>, S>

      Takes this stream and returns value. If it throws an error, the resulting ITry is not successful.

    Returns ITry<S>

    The result of the operation, wrapped in a ITry for encapsulating thrown errors.

tryEnd

  • tryEnd(): ITry<void>
  • Same as {@link #end}, but encapsulates any errors thrown. Applies all pending operation to the pipeline.

    // prints 1,2,3
    stream([1,2,3]).visit(console.log).tryEnd()
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Returns ITry<void>

    The encapsulated error, if any was thrown.

unique

  • unique(comparator?: Comparator<T>): this
  • Filters all elements that are considered equal according to the given comparator. If two items are equal, the first one encountered is included in the resulting stream. Consider using {@link #uniqueBy} if possible for better performance.

    stream([4,1,3,4,1,3,1,9]).unique()
    // => Stream[4,1,3,9]
    
    stream({id:4},{id:2},{id:4]}).unique((x,y) => x.id - y.id)
    // => Stream[ {id:4}, {id:2} ]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Optional comparator: Comparator<T>

      Takes two items and returns 0 if they are equal. Defaults to taking determining equality by ===.

    Returns this

    A stream with all duplicates removed.

uniqueBy

  • uniqueBy<K>(keyExtractor: TypedFunction<T, K>): this
  • Similar to {@link #unique}, but allows for a custom key to be specified, according to which uniqueness is determined. If two items compare equal, the item encountered first in the stream is taken. If items with the same key need to be merged, consider using stream.collect(Collectors.toSet(merger)).

    stream([4,1,3,4,1,3,1,9]).distinct()
    // => Stream[4,1,3,9]
    
    stream({id:4},{id:2},{id:4]}, customer => customer.id).distinct()
    // => Stream[ {id:4}, {id:2} ]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • K

    Parameters

    • keyExtractor: TypedFunction<T, K>

      Returns a key for each item. Items with duplicate keys are removed. Defaults to taking the item itself as the key.

    Returns this

    A stream with all duplicates removed.

visit

  • visit(consumer: Consumer<T>): this
  • Calls the given consumer once for each item. Note that the consumer is not called before the stream is consumed by some terminal operation.

    stream([1,2,3]).visit(console.log)
    // => Stream[1,2,3]
    // prints `1,2,3` once the stream is consumed.
    
    infinite_stream

    Hangs when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • consumer: Consumer<T>

      Callback taking each item.

    Returns this

    A stream with the same items as this stream.

zip

  • zip<S>(other: Iterable<S>): IStream<[Maybe<T>, Maybe<S>]>
  • Produces a stream over tuples of consisting of an item of the given iterable; and the corresponding item of the other iterable. If one of the iterables is longer, the shorter one is appended with undefined.

    stream(["foo", "bar"].zip([3, 4])
    // => Stream[ ["foo",3], ["bar", 4] ]
    
    stream(["foo", "bar"]).zip([3, 4]).toMap(x=>x[0], x=>x[1])
    // => Map[ "foo" => 3, "bar" => 4] ]
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Type parameters

    • S

    Parameters

    • other: Iterable<S>

      Other iterable to be zipped to this stream.

    Returns IStream<[Maybe<T>, Maybe<S>]>

    A stream over all the produced tuples.

zipSame

  • zipSame(...others: Iterable<T>[]): IStream<Maybe<T>[]>
  • Produces a stream over tuples of consisting of an item of this stream 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.

    stream("ab").zipSame(["cd", "ef"])
    // => Iterable[ ["a","c", "d"], ["b", "d", "f"] ]
    
    stream("abc").zipSame(["d", "ef"])
    // => Iterable[ ["a","d", "e"], ["b", undefined, "f"], ["c", undefined, undefined] ]
    
    stream("fb").zipSame(["oa","or"]).map(x=>x.map(String).join("")).join("").toArray()
    // => "foobar"
    
    infinite_stream

    Does not hang when used on infinite (unlimited) streams.

    terminal

    This is a terminal operation. The original stream object must not be used anymore.

    Parameters

    • Rest ...others: Iterable<T>[]

      Other iterable to be zipped to the given iterable.

    Returns IStream<Maybe<T>[]>

    A stream over al the produced tuples.

Generated using TypeDoc