Skip to content

Instantly share code, notes, and snippets.

@rbuckton
Forked from mattpodwysocki/mapasync.ts
Last active May 30, 2017 19:33
Show Gist options
  • Save rbuckton/c60954f23effa3992f9151d72ba7431d to your computer and use it in GitHub Desktop.
Save rbuckton/c60954f23effa3992f9151d72ba7431d to your computer and use it in GitHub Desktop.
'use strict';
class MapAsyncIterable<T, R> implements AsyncIterable<R> {
private _source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>;
private _selector: (value: T) => R | PromiseLike<R>;
constructor(source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>, selector: (value: T) => R | PromiseLike<R>) {
this._source = source;
this._selector = selector;
}
async *[Symbol.asyncIterator]() {
for await (let item of this._source as AsyncIterable<T>) { // workaround for https://github.com/Microsoft/TypeScript/issues/16153
let result = await this._selector(item);
yield result;
}
}
}
export function mapAsync<T, R>(
source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>,
selector: (this: undefined, value: T) => R | PromiseLike<R>,
thisArg?: undefined | null): AsyncIterable<R>;
export function mapAsync<T, R, This>(
source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>,
selector: (this: This, value: T) => R | PromiseLike<R>,
thisArg: This): AsyncIterable<R>;
export function mapAsync<T, R>(
source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>,
selector: (value: T) => R | PromiseLike<R>,
thisArg?: any): AsyncIterable<R> {
const fn = selector.bind(thisArg);
return new MapAsyncIterable<T, R>(source, fn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment