Options
All
  • Public
  • Public/Protected
  • All
Menu
author

James Errington james.errington@protonmail.com

since

1.0.0

A wrapper class that encapsulates a lazyily-evaluated iterable; a synchronous list of values that are generated on-demand.

Type parameters

Hierarchy

  • LazyIterable

Index

Constructors

constructor

  • new LazyIterable<T>(generator: Generator<T, any, unknown>): LazyIterable<T>
  • example

    Create a new LazyIterable from a generator function:

    function* generator() {
      for (let i = 0; i < 10; i++) {
        yield i
      }
    }
    
    const iterable = new LazyIterable(generator())
    
    since

    1.0.0

    Type parameters

    • T

    Parameters

    • generator: Generator<T, any, unknown>

      The generator to be wrapped in the LazyIterable

    Returns LazyIterable<T>

Lazy Methods

drop

  • Returns a new LazyIterable that ignores the first items values from the base generator before yielding.

    example

    Drop 3 values before yielding

    LazyIterable.fromIterable([1, 2, 3, 4, 5]).drop(3).toArray() // Returns [4, 5]
    
    see

    LearnRxJS - skip for the RxJS version

    since

    1.0.0

    Parameters

    • items: number

      The number of values to ignore from the generator

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

dropWhile

  • dropWhile(predicate: (value: T, index: number) => boolean): LazyIterable<T>
  • Returns a new LazyIterable that ignores values from the base generator until the provided predicate is false.

    example

    Drop values until a threshold is first met

    const numbers = [1, 2, 3, 4, 3, 2, 6]
    LazyIterable.fromIterable(numbers).dropWhile(value => value < 4).toArray() // Returns [4, 3, 2, 6]
    
    see

    LearnRxJS - skipWhile for the RxJS version

    since

    1.0.0

    Parameters

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

          • value: T
          • index: number

          Returns boolean

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

feedTo

  • feedTo<S>(generatorFunc: (seed: Iterable<T>) => Generator<S, any, unknown>): LazyIterable<S>
  • Returns a new LazyIterable that yields the values returned from calling the provided generator with values from the base generator. Can be considered a generalisation of the other lazy processing methods, and is useful when more complex processing is required; for example, when stateful knowledge of past values is needed.

    example

    Chunk an array of strings into set lengths and apply processing

    // Generator function to chunk strings into lengths of 5
    function* chunk(stringIterable: Iterable<string>) {
      let previous = "" // We require knowledge of past values yielded from the generator
      for (const value of stringIterable) {
        previous += value
        if (previous.length > 5) {
          yield previous.substr(0, 5)
          previous = previous.substring(5)
        }
      }
      if (previous.length > 0) {
        yield previous
      }
    }
    
    const strings = ["ABC", "DEFGHI", "JKLMN", "OPQRSTU", "VWXY", "Z"]
    // With a LazyIterable, we can perform the chunking and the lower case conversion without needing a custom 'Lowercase Chunk' generator
    LazyIterable
      .fromIterable(strings)
      .feedTo(chunk)
      .map(value => value.toLowerCase())
      .toArray() // Returns ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
    
    since

    1.0.0

    Type parameters

    • S

    Parameters

    • generatorFunc: (seed: Iterable<T>) => Generator<S, any, unknown>
        • (seed: Iterable<T>): Generator<S, any, unknown>
        • Parameters

          • seed: Iterable<T>

          Returns Generator<S, any, unknown>

    Returns LazyIterable<S>

    A new LazyIterable, for chaining

filter

  • filter(predicate: (value: T, index: number) => boolean): LazyIterable<T>
  • Returns a new LazyIterable that yields only those values from the base generator for which the provided predicate is true.

    example

    Filter values below a threshold

    const numbers = [1, 2, 3, 4, 3, 2, 6]
    LazyIterable.fromIterable(numbers).filter(value => value < 4).toArray() // Returns [1, 2, 3, 3, 2]
    
    see

    MDN - Array.prototype.filter() for the standard Array method.

    since

    1.0.0

    Parameters

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

          • value: T
          • index: number

          Returns boolean

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

map

  • map<S>(callback: (value: T, index: number) => S): LazyIterable<S>
  • Returns a new LazyIterable that yields the result of applying the provided callback to values from the base generator.

    example

    Convert yielded values to uppercase

    const strings = ["a", "b", "c", "def"]
    LazyIterable
      .fromIterable(strings)
      .map(value => value.toUpperCase())
      .toArray() // Returns ["A", "B", "C", "DEF"]
    
    see

    MDN - Array.prototype.map() for the standard Array method.

    since

    1.0.0

    Type parameters

    • S

      The type returned by the callback

    Parameters

    • callback: (value: T, index: number) => S
        • (value: T, index: number): S
        • Parameters

          • value: T
          • index: number

          Returns S

    Returns LazyIterable<S>

    A new LazyIterable, for chaining

runEffect

  • runEffect(effect: (value: T, index: number) => unknown): LazyIterable<T>
  • Performs an effectful callback effect for each value yielded from the base generator, and returns a new LazyIterable that just passes the values on. Can be considered a helper function for an effectful map on the identity function, or a lazy version of forEach.

    example

    Insert a logging utility function inside a LazyIterable chain

    LazyIterable.fromIterable([1, 2, 3]).runEffect(value => console.log(value)).map(value => value * 2).toArray()
    // Logs 1, 2, 3 to the console, and returns [2, 4, 6]
    
    since

    1.0.0

    Parameters

    • effect: (value: T, index: number) => unknown
        • (value: T, index: number): unknown
        • Parameters

          • value: T
          • index: number

          Returns unknown

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

take

  • Returns a new LazyIterable that yields the first items number of values from the base generator.

    example

    Convert an infinite generator to a finite one

    LazyIterable.fromIterable([1, 2, 3, 4, 5]).take(3).toArray() // Returns [1, 2, 3]
    
    see

    LearnRxJS - take for the RxJS version

    since

    1.0.0

    Parameters

    • items: number

      The number of values to take from the generator

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

takeWhile

  • takeWhile(predicate: (value: T, index: number) => boolean): LazyIterable<T>
  • Returns a new LazyIterable that yields values from the base generator until the provided predicate is false. This is different to filter in that no values after the first false response are yielded.

    example

    takeWhile vs filter

    const numbers = [1, 2, 3, 4, 3, 2, 6]
    LazyIterable.fromIterable(numbers).takeWhile(value => value < 4).toArray() // Returns [1, 2, 3]
    
    LazyIterable.fromIterable(numbers).filter(value => value < 4).toArray() // Returns [1, 2, 3, 3, 2]
    
    see

    LearnRxJS - takeWhile for the RxJS version

    since

    1.0.0

    Parameters

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

          • value: T
          • index: number

          Returns boolean

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

Eager Methods

every

  • every(predicate: (value: T, index: number) => boolean): boolean
  • Tests values yielded from the LazyIterable against the given predicate, returning true if it is satisfied every time. As an eager method, calling every will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Test for all even numbers

    LazyIterable.fromIterable([1, 2, 3, 4, 5]).every(value => value % 2 === 0) // Returns false
    
    see

    MDN - Array.prototype.every() for the standard Array method.

    since

    1.0.0

    Parameters

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

          • value: T
          • index: number

          Returns boolean

    Returns boolean

    true if every value satisfies the given predicate, else false.

find

  • find(predicate: (value: T, index: number) => boolean): undefined | T
  • Returns the first value yielded by the LazyIterable that satisfies the given predicate. As an eager method, calling find will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Find a value yielded from a LazyIterable

    const strings = ["A", "BC", "DEF", "HIJK"]
    LazyIterable.fromIterable(strings).find(value => value.length > 2) // Returns "DEF"
    
    see

    MDN - Array.prototype.find() for the standard Array method.

    since

    1.0.0

    Parameters

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

          • value: T
          • index: number

          Returns boolean

    Returns undefined | T

    The value of the first element that satisfies the given predicate, or undefined if no value exists.

forEach

  • forEach(callback: (value: T, index: number) => unknown): void
  • Similar to runEffect, calls the given callback for each value yielded from the LazyIterable, but does not return a new iterable. As an eager method, calling forEach will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Log values from a LazyIterable

    LazyIterable.fromIterable([1, 2, 3, 4, 5]).forEach(value => console.log(value))
    // Logs 1, 2, 3, 4, 5 each on a new line
    
    see

    MDN - Array.prototype.forEach() for the standard Array method.

    since

    1.0.0

    Parameters

    • callback: (value: T, index: number) => unknown
        • (value: T, index: number): unknown
        • Parameters

          • value: T
          • index: number

          Returns unknown

    Returns void

includes

  • includes(search: T): boolean
  • Determines if the LazyIterable yielded a given value search. As an eager method, calling includes will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Test if a value was yielded

    LazyIterable.fromIterable(["apple", "orange", "pear"]).includes("pear") // Returns true
    
    see

    MDN - Array.prototype.includes() for the standard Array method.

    since

    1.0.0

    Parameters

    • search: T

      The value to search for.

    Returns boolean

    true if the given value was yielded, else false.

indexOf

  • indexOf(search: T): number
  • Returns the index of the value that matches the given search value; in a LazyIterable, this translates to the number of values that have been yielded before an instance of search is found. As an eager method, calling indexOf will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Count values yielded before a given value

    LazyIterable.fromIterable(["A", "B", "C", "D"]).indexOf("C") // Returns 2
    LazyIterable.fromIterable(["A", "B", "C", "D"]).indexOf("E") // Returns -1
    
    see

    MDN - Array.prototype.indexOf() for the standard Array method.

    since

    1.0.0

    Parameters

    • search: T

      The value to search for.

    Returns number

    How many values had been yielded from the LazyIterable before search, or -1 if search is never yielded.

join

  • join(separator?: string): string
  • Returns a string formed by concatenating each element yielded from the LazyIterable, separated by the given separator, or a comma ',' if none is provided. If only one value is yielded, that value is returned as a string with no seperator. If no values are yielded, an empty string is returned. As an eager method, calling join will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Build a string from elements of a LazyIterable

    LazyIterable.fromIterable(["First", "Second", "Third"].join(" ") // Returns "First Second Third"
    LazyIterable.fromIterable(["First", "Second", "Third"].join()    // Returns "First,Second,Third"
    
    see

    MDN - Array.prototype.join() for the standard Array method.

    since

    1.0.0

    Parameters

    • separator: string = ","

      The string that will separate elements in the final string. Defaults to comma ',' if none is provided.

    Returns string

    A string with each element of the LazyIterable joined.

lastIndexOf

  • lastIndexOf(search: T): number
  • Returns the last index of the value that matches the given search value; in a LazyIterable, this translates to the number of values that have been yielded before the last instance of search is found. As an eager method, calling lastIndexOf will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases. The LazyIterable must also be finite for this method to work.

    Note the difference between this method and the standard Array implementation; because a LazyIterable encapsulates a stream of values that have yet to be fully evaluated, lastIndexOf cannot search backwards, and so this method on its own is likely much less efficient.

    example

    Count values yielded before the last instance of a given value

    LazyIterable.fromIterable(["A", "B", "C", "A"]).indexOf("A") // Returns 3
    LazyIterable.fromIterable(["A", "B", "C", "D"]).indexOf("E") // Returns -1
    
    see

    MDN - Array.prototype.lastIndexOf() for the standard Array method.

    since

    1.0.0

    Parameters

    • search: T

      The value to search for.

    Returns number

    How many values had been yielded from the LazyIterable before the last instance of search, or -1 if search is never yielded.

next

  • next(): IteratorResult<T, any>
  • Returns an object with two properties: value, and done. value holds the next value of the iteration sequence, based on the current state of the internal generator. done is true if the last value of the generator has already been consumed, otherwise false.

    example

    Using the next method to manually iterate a LazyIterable

    const iterable = LazyIterable.fromIterable([1, 2, 3])
    iterable.next() // Returns { value: 1, done: false }
    iterable.next() // Returns { value: 2, done: false }
    iterable.next() // Returns { value: 3, done: false }
    iterable.next() // Returns { value: undefined, done: true }
    // All subsequent calls to next() return { value: undefined, done: true }
    
    see

    MDN - Iterators and generators for more detail

    since

    1.0.0

    Returns IteratorResult<T, any>

    The result from one iteration of the generator

reduce

  • reduce<S>(reducer: (accumulator: S, value: T, index: number) => S, initial: S): S
  • Applies the given reducer function for each value yielded from the LazyIterable, returning a single output value. As an eager method, calling reduce will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Sum the values yielded by a LazyIterable

    function sumReducer(accumulator: number, value: number) {
      return accumulator + value
    }
    LazyIterable.fromIterable([1, 2, 3, 4, 5]).reduce(sumReducer, 0) // Returns 15
    
    see

    MDN - Array.prototype.reduce() for the standard Array method.

    since

    1.0.0

    Type parameters

    • S

      The type of the accumulated value

    Parameters

    • reducer: (accumulator: S, value: T, index: number) => S

      The function to apply for each value yielded

        • (accumulator: S, value: T, index: number): S
        • Parameters

          • accumulator: S
          • value: T
          • index: number

          Returns S

    • initial: S

      The initial value for the accumulator

    Returns S

    The final result of the reduction

reverse

  • Returns a new LazyIterable that yields the values of the original LazyIterable in reverse order. As an eager method, calling reverse will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Reverse a LazyIterable

    LazyIterable.fromIterable(["A", "B", "C", "D"]).reverse().toArray() // Returns ["D", "C", "B", "A"]
    
    see

    MDN - Array.prototype.reverse() for the standard Array method.

    since

    1.0.0

    Returns LazyIterable<T>

    A new LazyIterable, for chaining

some

  • some(predicate: (value: T, index: number) => boolean): boolean
  • Tests values yielded from the LazyIterable against the given predicate, returning true if it is satisfied at least once. As an eager method, calling some will trigger an evaluation of the LazyIterable. Since values cannot be re-yielded once run, it may be more appropriate to use the standard Array method for some use cases.

    example

    Test for at least one even number

    LazyIterable.fromIterable([1, 2, 3, 4, 5]).some(value => value % 2 === 0) // Returns true
    
    see

    MDN - Array.prototype.some() for the standard Array method.

    since

    1.0.0

    Parameters

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

          • value: T
          • index: number

          Returns boolean

    Returns boolean

    true if at least one value satisfies the given predicate, else false.

Conversion Methods

toArray

  • toArray(): T[]
  • Returns a standard Array containing the values yielded from the LazyIterable in order. This is an eager method, which means it requires the evaluation of the LazyIterable; therefore, you must ensure that the underlying LazyIterable is not infinite.

    As this method relies on the standard Array.from() method, it returns a shallow copied Array.

    example

    Convert a LazyIterable to a standard Array

    LazyIterable.fromIterable(["A", "B", "C", "D"]).toArray() // Returns ["A", "B", "C", "D"]
    
    see

    MDN - Array.reverse() for the standard Array method.

    since

    1.0.0

    Returns T[]

    A new Array instance

toAsyncIterable

Static fromIterable

  • Converts an Iterable into a new LazyIterable. The input can be anything that implements the @@iterator method; common built-in iterables include Array, String, Set, and Map.

    example

    Convert a built in Iterable to a LazyIterable:

    // Array and String are common iterables
    const arrayIterable = LazyIterable.fromIterable([1, 2, 3, 4, 5])
    const stringIterable = LazyIterable.fromIterable("Hello world!")
    
    // `Set` and `Map` are also both iterable
    const set = new Set([1, 2, 1, 3, 2, 2])
    const setIterable = LazyIterable.fromIterable(set)
    
    const map = new Map([["A", 1], ["B", 2], ["C", 3]])
    const mapIterable = LazyIterable.fromIterable(map)
    
    example

    Convert a custom Iterable into a LazyIterable

    const customIterable = {
      *[Symbol.iterator]() {
        yield 1
        yield 2
      }
    }
    const lazyIterable = LazyIterable.fromIterable(customIterable)
    
    see

    MDN - Iterators and generators for more detail

    since

    1.0.0

    Type parameters

    • S

      The type returned from the input iterable

    Parameters

    • iterable: Iterable<S>

    Returns LazyIterable<S>

    A new LazyIterable

Legend

  • Method

Generated using TypeDoc