Function stream

  • Creates a Stream from an iterable (e.g., array, set, etc.) or a function that returns an iterator (such as a generator function). Streams created with this function never modify input; if you need the opposite, use streamFromModifiable.

    Type Parameters

    • T

      The type of the stream's items.

    Parameters

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

      The source to create the stream from. The input can be an iterable, such as an array, set, or map, or a function that returns an iterator, such as a generator function.

    Returns Stream<T>

    A Stream created from the provided input.

    // Prints 1, 2, 3
    stream([1, 2, 3])
    .forEach(i => console.log(i))
    // Prints 1, 2, 3
    stream(function* () {
    yield 1
    yield 2
    yield 3
    })
    .forEach(i => console.log(i))
    // Prints 1, 2, 3
    stream({
    [Symbol.iterator]() {
    let i = 1
    return {
    next() {
    return i <= 3
    ? {value: i++, done: false}
    : {value: undefined, done: true}
    }
    }
    }
    })
    .forEach(i => console.log(i))

    If you implement your own iterator, note the following:

    • next() arguments, if any, are not used.
    • value returned with {done: true} is ignored.
    • return() and throw() methods are not utilized.