Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active May 15, 2017 00:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/34e76e199442971885a4f48c0730aa40 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/34e76e199442971885a4f48c0730aa40 to your computer and use it in GitHub Desktop.
Implementations of `flatten` and `flatMap` as described in the [ES Proposal](https://bterlson.github.io/proposal-flatMap/)
'use strict';
import { bindCallback } from '../internal/bindcallback';
export async function *flatMapAsync<TSource, TResult>(
source: AsyncIterable<TSource>,
fn: (value: TSource) => AsyncIterable<TResult>,
thisArg?: any): AsyncIterable<TResult> {
let sel = bindCallback(fn, thisArg, 1);
for await (let outerItem of source) {
for await (let innerItem of sel(outerItem)) {
yield innerItem;
}
}
}
'use strict';
import { bindCallback } from '../internal/bindcallback';
export async function *flatMapAsync<TSource, TResult>(
source: AsyncIterable<TSource>,
fn: (value: TSource) => AsyncIterable<TResult>,
thisArg?: any): AsyncIterable<TResult> {
let sel = bindCallback(fn, thisArg, 1);
for await (let outerItem of source) {
for await (let innerItem of sel(outerItem)) {
yield innerItem;
}
}
}
'use strict';
import { bindCallback } from '../internal/bindcallback';
export async function *flatMapAsync<TSource, TResult>(
source: AsyncIterable<TSource>,
fn: (value: TSource) => AsyncIterable<TResult>,
thisArg?: any): AsyncIterable<TResult> {
let sel = bindCallback(fn, thisArg, 1);
for await (let outerItem of source) {
for await (let innerItem of sel(outerItem)) {
yield innerItem;
}
}
}
'use strict';
import { isAsyncIterable } from '../internal/isasynciterable';
export async function *flattenAsync<T>(iterable: AsyncIterable<T>, depth: number = Infinity): AsyncIterable<T> {
if (depth === 0) { return iterable; }
for await (let item of iterable) {
if (isAsyncIterable(item)) {
yield *flattenAsync(item, depth - 1);
} else {
yield item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment