Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created May 30, 2017 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/186cf6f34cfc65227dab1dc414a98e67 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/186cf6f34cfc65227dab1dc414a98e67 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) => Promise<R> | R;
constructor(
source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>,
selector: (value: T) => Promise<R> | R) {
this._source = source;
this._selector = selector;
}
async *[Symbol.asyncIterator]() {
for await (let item of <AsyncIterable<T>>(this._source)) {
let result = await this._selector(item);
yield result;
}
}
}
export function mapAsync<T, R>(
source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>,
selector: (value: T) => Promise<R>,
thisArg?: any): AsyncIterable<R> {
const fn = selector.bind(thisArg);
return new MapAsyncIterable<T, R>(source, fn);
}
@marcinnajder
Copy link

pure beauty :) it's worth to add R here selector: (value: T) => Promise<R>|R

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment