Options
All
  • Public
  • Public/Protected
  • All
Menu

Async Iterable Functions

npm version GitHub issues TypeDoc docs Travis Coveralls Dev Dependencies styled with prettier

Really simple functions for working with async iterable types, inspired by F#'s collection modules design.

Features

  • Full type-safety with TypeScript
  • Zero dependency
  • Pure functions

Installation

Add package using NPM or yarn

npm i --save async-iterable-fns
yarn add async-iterable-fns

You can import the top level modules directly:

import { groupBy } from 'async-iterable-fns'

Examples

Calculating primes lazily with iterators can either be done by calling each of the basic functions:

import { count, initRaw, map, filter } from 'async-iterable-fns'

const findPrimes = async () => {
  const range = initRaw({ from: 1, to: 100 })
  const mapped = map(range, (x) => ({
    x,
    factors: filter(initRaw({ from: 1, to: x }), (y) => x % y === 0),
  }))
  const filtered = filter(mapped, async (num) => (await count(num.factors)) === 2)
  const primes = map(filtered, (num) => num.x)
  return await toArray(primes)
}

or can utilise the chainable methods:

import { init } from 'async-iterable-fns'

const findPrimesChained = async () => {
  const primes = init({ from: 1, to: 100 })
    .map((x) => ({
      x,
      factors: init({ from: 1, to: x }).filter((y) => x % y === 0),
    }))
    .filter(async (num) => (await num.factors.count()) === 2)
    .map((num) => num.x)

  for await (const prime of primes) {
    console.log(prime)
  }
}

NPM scripts

  • yarn test: Run test suite
  • yarn start: Run yarn build in watch mode
  • yarn test:watch: Run test suite in interactive watch mode
  • yarn test:prod: Run linting and generate coverage
  • yarn build: Generate bundles and typings, create docs
  • yarn lint: Lints code
  • yarn commit: Commit using conventional commit style (husky will tell you to use it if you haven't :wink:)

Index

Variables

Const length

length: count = count

Returns the number of items in the collection.

param

The input collection.

alias

count

example

await length(init(5)) // Returns: 5

Functions

append

  • append<T>(first: AsyncIterable<T>, second: AsyncIterable<T>): AsyncIterable<T>
  • Wraps the two given iterables as a single concatenated iterable.

    example

    append( init({ from: 1, to: 3 }), init({ from: 8, to: 10 }) ) // Yields: 1, 2, 3, 8, 9, 10

    Type parameters

    • T

    Parameters

    • first: AsyncIterable<T>

      The first iterable.

    • second: AsyncIterable<T>

      The second iterable.

    Returns AsyncIterable<T>

chain

  • Create a new chainable iterator from an existing iterable source.

    example

    async function* source() { yield { name: 'CAT', age: 18 } yield { name: 'Amy', age: 21 } yield { name: 'bob', age: 2 } } await chain(source()) .filter((x) => x.age >= 18) .map((x) => x.name) .sortBy((x) => x.toLowerCase()) .toArray()

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    Returns ChainableAsyncIterable<T>

choose

  • choose<T, U>(source: AsyncIterable<T>, chooser: (item: T, index: number) => U | undefined | Promise<U | undefined>): AsyncIterable<U>
  • Applies the given function to each element of the sequence and returns a new sequence comprised of the results for each element where the function returns a value. This can be thought of as doing both a filter and a map at the same time.

    example

    choose( init({ from: 1, to: 3 }), (x) => (x % 2 === 1 ? x * 2 : undefined) ) // Yields: 2, 6

    Type parameters

    • T

    • U

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • chooser: (item: T, index: number) => U | undefined | Promise<U | undefined>

      A function to transform items from the input collection to a new value to be included, or undefined to be excluded.

        • (item: T, index: number): U | undefined | Promise<U | undefined>
        • Parameters

          • item: T
          • index: number

          Returns U | undefined | Promise<U | undefined>

    Returns AsyncIterable<U>

collect

  • collect<T, U>(source: AsyncIterable<T>, mapping: (item: T, index: number) => Iterable<U> | AsyncIterable<U>): AsyncIterable<U>
  • Applies the given function to each element of the source iterable and concatenates all the results.

    example

    collect( init({ from: 1, to: 3 }), function* (x) { yield x yield x } ) // Yields: 1, 1, 2, 2, 3, 3

    // You can also just return an array from your mapping function collect( init({ from: 1, to: 3 }), (x) => [x, x] )

    Type parameters

    • T

    • U

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • mapping: (item: T, index: number) => Iterable<U> | AsyncIterable<U>

      A function to transform elements of the input collection into collections that are concatenated.

        • (item: T, index: number): Iterable<U> | AsyncIterable<U>
        • Parameters

          • item: T
          • index: number

          Returns Iterable<U> | AsyncIterable<U>

    Returns AsyncIterable<U>

concat

  • concat<T>(sources: AsyncIterable<Iterable<T> | AsyncIterable<T>> | Iterable<Iterable<T> | AsyncIterable<T>>): AsyncIterable<T>
  • Combines the given collection-of-iterables as a single concatenated iterable.

    example

    concat([ init({ from: 1, to: 2 }), init({ from: 4, to: 5 }), init({ from: 8, to: 9 }) ]) // Yields 1, 2, 4, 5, 8, 9

    Type parameters

    • T

    Parameters

    • sources: AsyncIterable<Iterable<T> | AsyncIterable<T>> | Iterable<Iterable<T> | AsyncIterable<T>>

      The input collection.

    Returns AsyncIterable<T>

count

  • count<T>(source: AsyncIterable<T>): Promise<number>
  • Returns the number of items in the collection.

    example

    await count(init(5)) // Returns: 5

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    Returns Promise<number>

distinct

  • distinct<T>(source: AsyncIterable<T>): AsyncIterable<T>
  • Returns a iterable that contains no duplicate entries according to the equality comparisons on the elements. If an element occurs multiple times in the sequence then the later occurrences are discarded.

    example

    async function* source() { yield 'bob' yield 'cat' yield 'bob' yield 'amy' } distinct(source()) // Yields: 'bob', 'cat', 'amy'

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    Returns AsyncIterable<T>

distinctBy

  • distinctBy<T, Key>(source: AsyncIterable<T>, selector: (item: T, index: number) => Key | Promise<Key>): AsyncIterable<T>
  • Returns a iterable that contains no duplicate entries according to the equality comparisons on the keys returned by the given key-generating function. If an element occurs multiple times in the sequence then the later occurrences are discarded.

    example

    async function* source() { yield { name: 'amy', id: 1 } yield { name: 'bob', id: 2 } yield { name: 'bob', id: 3 } yield { name: 'cat', id: 3 } } distinctBy(source(), (x) => x.name) // Yields: // { name: 'amy', id: 1 } // { name: 'bob', id: 2 } // { name: 'cat', id: 3 }

    Type parameters

    • T

    • Key

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T, index: number) => Key | Promise<Key>

      A function that transforms the collection items into comparable keys.

        • (item: T, index: number): Key | Promise<Key>
        • Parameters

          • item: T
          • index: number

          Returns Key | Promise<Key>

    Returns AsyncIterable<T>

every

  • every<T>(source: AsyncIterable<T>, predicate: (item: T, index: number) => boolean | Promise<boolean>): Promise<boolean>
  • Tests if every element of the collection satisfies the given predicate.

    example

    await every(init({ from: 1, to: 3 }), (x) => x > 0) // Returns: true

    await every(init({ from: 1, to: 3 }), (x) => x < 2) // Returns: false

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

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

      A function to test against each item of the input collection.

        • (item: T, index: number): boolean | Promise<boolean>
        • Parameters

          • item: T
          • index: number

          Returns boolean | Promise<boolean>

    Returns Promise<boolean>

exists

  • exists<T>(source: AsyncIterable<T>, predicate: (item: T, index: number) => boolean | Promise<boolean>): Promise<boolean>
  • Tests if any element of the collection satisfies the given predicate.

    example

    await exists(init({ from: 1, to: 3 }), (x) => x === 2) // Returns: true

    await exists(init({ from: 1, to: 3 }), (x) => x === 4) // Returns: false

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

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

      A function to test each item of the input collection.

        • (item: T, index: number): boolean | Promise<boolean>
        • Parameters

          • item: T
          • index: number

          Returns boolean | Promise<boolean>

    Returns Promise<boolean>

filter

  • filter<T>(source: AsyncIterable<T>, predicate: (item: T, index: number) => boolean | Promise<boolean>): AsyncIterable<T>
  • Returns a new iterable containing only the elements of the collection for which the given predicate returns true.

    example

    filter( init({ from: 1, to: 4 }), (x) => x % 2 === 0 ) // Yields: 2, 4

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

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

      A function to test whether each item in the input collection should be included in the output.

        • (item: T, index: number): boolean | Promise<boolean>
        • Parameters

          • item: T
          • index: number

          Returns boolean | Promise<boolean>

    Returns AsyncIterable<T>

find

  • find<T>(source: AsyncIterable<T>, predicate: (item: T, index: number) => boolean | Promise<boolean>): Promise<T | undefined>
  • Returns the first element for which the given function returns true, otherwise undefined.

    example

    async function* source() { yield { name: 'amy', id: 1 } yield { name: 'bob', id: 2 } } await find(source(), (p) => p.name === 'bob') // Returns: { name: 'bob', id: 2 } await find(source(), (p) => p.name === 'cat') // Returns: undefined

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

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

      A function to test whether an item in the collection should be returned.

        • (item: T, index: number): boolean | Promise<boolean>
        • Parameters

          • item: T
          • index: number

          Returns boolean | Promise<boolean>

    Returns Promise<T | undefined>

get

  • get<T>(source: AsyncIterable<T>, predicate: (item: T, index: number) => boolean | Promise<boolean>): Promise<T>
  • Returns the first element for which the given function returns true.

    throws

    If no item is found matching the criteria of the predicate.

    example

    async function* source() { yield { name: 'amy', id: 1 } yield { name: 'bob', id: 2 } } await get(source(), (p) => p.name === 'bob') // Returns: { name: 'bob', id: 2 }

    await get(source(), (p) => p.name === 'cat') // Throws: Element not found matching criteria

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

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

      A function to test whether an item in the collection should be returned.

        • (item: T, index: number): boolean | Promise<boolean>
        • Parameters

          • item: T
          • index: number

          Returns boolean | Promise<boolean>

    Returns Promise<T>

groupBy

  • groupBy<T, Key>(source: AsyncIterable<T>, selector: (item: T, index: number) => Key | Promise<Key>): Promise<Map<Key, T[]>>
  • Applies a key-generating function to each element of a collection and yields a iterable of unique keys and an array of all elements that have each key.

    NOTE: Requires complete iteration of source before yielding first element.

    example

    async function* source() { yield { name: 'amy', age: 1 } yield { name: 'bob', age: 2 } yield { name: 'cat', age: 2 } } await groupBy(source(), (x) => x.age) // Returns a Map: // 1, [{ name: 'amy', age: 1 }] // 2, [{ name: 'bob', age: 2 }, { name: 'cat', age: 2 }]

    Type parameters

    • T

    • Key

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T, index: number) => Key | Promise<Key>

      A function that transforms an element of the collection into a comparable key.

        • (item: T, index: number): Key | Promise<Key>
        • Parameters

          • item: T
          • index: number

          Returns Key | Promise<Key>

    Returns Promise<Map<Key, T[]>>

init

  • Generates a new chainable iterable which, when iterated, will return the specified number sequence.

    throws

    When the options would result in a sequence that would not complete. If this is the desired behaviour, use initInfinite.

    example

    init(3) // Yields: 0, 1, 2 init({ from: 2, to: 5 }) // Yields: 2, 3, 4, 5 init({ from: 0, to: 100, increment: 25 }) // Yields: 0, 25, 50, 75, 100

    Parameters

    Returns ChainableAsyncIterable<number>

initInfinite

  • initInfinite(options?: undefined | { increment?: undefined | number; start?: undefined | number }): ChainableAsyncIterable<number>
  • Generates a new chainable iterable which, when iterated, will return the specified number sequence.

    example

    initInfinite() // Yields: 0, 1, 2, ... initInfinite({ start: 99 }) // Yields: 99, 100, 101 ... initInfinite({ start: 1, increment: -0.5 }) // Yields: 1, 0.5, 0, -0.5, -1, ...

    Parameters

    • Optional options: undefined | { increment?: undefined | number; start?: undefined | number }

      The sequence of numbers to generate.

    Returns ChainableAsyncIterable<number>

initInfiniteRaw

  • initInfiniteRaw(options?: undefined | { increment?: undefined | number; start?: undefined | number }): AsyncIterable<number>
  • Generates a new iterable which, when iterated, will return the specified number sequence.

    example

    initInfiniteRaw() // Yields: 0, 1, 2, ... initInfiniteRaw({ start: 99 }) // Yields: 99, 100, 101 ... initInfiniteRaw({ start: 1, increment: -0.5 }) // Yields: 1, 0.5, 0, -0.5, -1, ...

    Parameters

    • Optional options: undefined | { increment?: undefined | number; start?: undefined | number }

      The sequence of numbers to generate.

    Returns AsyncIterable<number>

initRaw

  • Generates a new iterable which, when iterated, will return the specified number sequence.

    throws

    When the options would result in a sequence that would not complete. If this is the desired behaviour, use initInfinite.

    example

    initRaw(3) // Yields: 0, 1, 2 initRaw({ from: 2, to: 5 }) // Yields: 2, 3, 4, 5 initRaw({ from: 0, to: 100, increment: 25 }) // Yields: 0, 25, 50, 75, 100

    Parameters

    Returns AsyncIterable<number>

map

  • map<T, U>(source: AsyncIterable<T>, mapping: (item: T, index: number) => U | Promise<U>): AsyncIterable<U>
  • Creates a new iterable whose elements are the results of applying the specified mapping to each of the elements of the source collection.

    example

    map( init({ from: 1, to: 3 }), (x) => x * 2 ) // Yields: 2, 4, 6

    Type parameters

    • T

    • U

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • mapping: (item: T, index: number) => U | Promise<U>

      A function to transform items from the input collection.

        • (item: T, index: number): U | Promise<U>
        • Parameters

          • item: T
          • index: number

          Returns U | Promise<U>

    Returns AsyncIterable<U>

max

  • max(source: AsyncIterable<number>): Promise<number>
  • Returns the maximum of the values in the collection.

    throws

    If the collection is empty.

    example

    await max(init({ from: 5, to: 10 })) // Returns: 10

    Parameters

    • source: AsyncIterable<number>

      The input collection.

    Returns Promise<number>

maxBy

  • maxBy<T>(source: AsyncIterable<T>, selector: (item: T) => number): Promise<number>
  • Returns the maximum of the values returned by the selector for each element in the collection.

    throws

    If the collection is empty.

    example

    async function* source() { yield { name: 'amy', age: 21 } yield { name: 'bob', age: 2 } yield { name: 'cat', age: 18 } } await maxBy(source(), (x) => x.age) // Returns: 21

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T) => number

      A function to transform each element into a comparable value.

        • (item: T): number
        • Parameters

          • item: T

          Returns number

    Returns Promise<number>

mean

  • mean(source: AsyncIterable<number>): Promise<number>
  • Returns the mean (average) of the values in the collection.

    throws

    If the collection is empty.

    example

    await mean(init({ from: 5, to: 10 })) // Returns: 7.5

    Parameters

    • source: AsyncIterable<number>

      The input collection.

    Returns Promise<number>

meanBy

  • meanBy<T>(source: AsyncIterable<T>, selector: (item: T) => number): Promise<number>
  • Returns the mean (average) of the values returned by the selector for each element in the collection.

    throws

    If the collection is empty.

    example

    async function* source() { yield { name: 'amy', age: 21 } yield { name: 'bob', age: 2 } yield { name: 'cat', age: 18 } yield { name: 'dot', age: 39 } } await meanBy(source(), (x) => x.age) // Returns: 20

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T) => number

      A function to transform each element into a summable value.

        • (item: T): number
        • Parameters

          • item: T

          Returns number

    Returns Promise<number>

min

  • min(source: AsyncIterable<number>): Promise<number>
  • Returns the minimum of the values in the collection.

    throws

    If the collection is empty.

    example

    await min(init({ from: 5, to: 10 })) // Returns: 5

    Parameters

    • source: AsyncIterable<number>

      The input collection.

    Returns Promise<number>

minBy

  • minBy<T>(source: AsyncIterable<T>, selector: (item: T) => number): Promise<number>
  • Returns the minimum of the values returned by the selector for each element in the collection.

    throws

    If the collection is empty.

    example

    async function* source() { yield { name: 'amy', age: 21 } yield { name: 'bob', age: 2 } yield { name: 'cat', age: 18 } } await minBy(source(), (x) => x.age) // Returns: 2

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T) => number

      A function to transform each element into a comparable value.

        • (item: T): number
        • Parameters

          • item: T

          Returns number

    Returns Promise<number>

pairwise

  • pairwise<T>(source: AsyncIterable<T>): AsyncIterable<[T, T]>
  • Returns an interable of each element in the input sequence and its predecessor, with the exception of the first element which is only returned as the predecessor of the second element.

    example

    pairwise(init({ from: 1, to: 4 })) // Yields: [1, 2], [2, 3], [3, 4]

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection

    Returns AsyncIterable<[T, T]>

reverse

  • reverse<T>(source: AsyncIterable<T>): Promise<T[]>
  • Yields each element of the iterable in reverse order.

    NOTE: Requires complete iteration of source before yielding first element.

    example

    async function* source() { yield 'cat' yield 'amy' yield 'bob' } await reverse(source()) // Returns: ['bob', 'amy', 'cat']

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    Returns Promise<T[]>

skip

  • skip<T>(source: AsyncIterable<T>, count: number): AsyncIterable<T>
  • Returns the elements of the iterable after a specified count.

    example

    skip(init({ from: 1, to: 5}), 2) // Yields: 3, 4, 5

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • count: number

      The number of items to skip.

    Returns AsyncIterable<T>

sort

  • sort<T, Key>(source: AsyncIterable<T>, selector?: undefined | ((item: T) => Key)): Promise<T[]>
  • Yields an iterable ordered by the selected key. If no selector is specified, the elements will be compared directly.

    NOTE: Requires complete iteration of source before yielding first element.

    example

    await sort(init({ from 3, to: 1 })) // Returns: [1, 2, 3]

    async function* source() { yield 'Cat' yield 'amy' yield 'BOB' } await sort(source(), (n) => n.toLowerCase()) // Returns: ['amy', 'BOB', 'Cat']

    Type parameters

    • T

    • Key

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • Optional selector: undefined | ((item: T) => Key)

      An optional function to transform items of the input sequence into comparable keys.

    Returns Promise<T[]>

sortBy

  • sortBy<T, Key>(source: AsyncIterable<T>, selector: (item: T) => Key): Promise<T[]>
  • Applies a key-generating function to each element of the collection and yields an iterable ordered by keys.

    NOTE: Requires complete iteration of source before yielding first element.

    example

    async function* source() { yield 'Cat' yield 'amy' yield 'BOB' } await sortBy(source(), (n) => n.toLowerCase()) // Returns: ['amy', 'BOB', 'Cat']

    Type parameters

    • T

    • Key

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T) => Key

      A function to transform items of the input sequence into comparable keys.

        • (item: T): Key
        • Parameters

          • item: T

          Returns Key

    Returns Promise<T[]>

sortByDescending

  • sortByDescending<T, Key>(source: AsyncIterable<T>, selector: (item: T) => Key): Promise<T[]>
  • Applies a key-generating function to each element of the collection and yields an iterable ordered by keys, descending.

    NOTE: Requires complete iteration of source before yielding first element.

    example

    async function* source() { yield 'Cat' yield 'amy' yield 'BOB' } await sortByDescending(source(), (n) => n.toLowerCase()) // Returns: ['Cat', 'BOB', 'amy']

    Type parameters

    • T

    • Key

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T) => Key

      A function to transform items of the input sequence into comparable keys.

        • (item: T): Key
        • Parameters

          • item: T

          Returns Key

    Returns Promise<T[]>

sortDescending

  • sortDescending<T, Key>(source: AsyncIterable<T>, selector?: undefined | ((item: T) => Key)): Promise<T[]>
  • Yields an iterable ordered by the selected key descending. If no selector is specified, the elements will be compared directly.

    NOTE: Requires complete iteration of source before yielding first element.

    example

    await sortDescending(init({ from 1, to: 3 })) // Returns: [3, 2, 1]

    async function* source() { yield 'Cat' yield 'amy' yield 'BOB' } await sortDescending(source(), (n) => n.toLowerCase()) // Returns: ['Cat', 'BOB', 'amy']

    Type parameters

    • T

    • Key

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • Optional selector: undefined | ((item: T) => Key)

      An optional function to transform items of the input sequence into comparable keys.

    Returns Promise<T[]>

sum

  • sum(source: AsyncIterable<number>): Promise<number>
  • Returns the sum of the values in the collection.

    example

    await sum(init({ from: 5, to: 10 })) // Returns: 45

    Parameters

    • source: AsyncIterable<number>

      The input collection.

    Returns Promise<number>

sumBy

  • sumBy<T>(source: AsyncIterable<T>, selector: (item: T) => number): Promise<number>
  • Returns the sum of the values returned by the selector for each element in the collection.

    example

    async function* source() { yield { name: 'amy', age: 21 } yield { name: 'bob', age: 2 } yield { name: 'cat', age: 18 } } await sumBy(source(), (x) => x.age) // Returns: 41

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • selector: (item: T) => number

      A function to transform each element into a summable value.

        • (item: T): number
        • Parameters

          • item: T

          Returns number

    Returns Promise<number>

take

  • take<T>(source: AsyncIterable<T>, count: number): AsyncIterable<T>
  • Returns the elements of the iterable up to a specified count.

    example

    take(init({ from: 1, to: 4 }), 2) // Yields: 1, 2

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      The input collection.

    • count: number

      The number of items to take.

    Returns AsyncIterable<T>

toArray

  • toArray<T>(source: AsyncIterable<T>): Promise<T[]>
  • Creates an array from the source async-iterable object.

    example

    async function* source() { yield 1 yield 2 } await toArray(source()) // Returns: [1, 2]

    Type parameters

    • T

    Parameters

    • source: AsyncIterable<T>

      An AsyncIterable objext to convert to an array.

    Returns Promise<T[]>

Legend

  • Constructor
  • Method
  • Property
  • Private property

Generated using TypeDoc