Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active March 31, 2020 07:41
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 OliverJAsh/03fa1e4b520ecda3311072adeec4912a to your computer and use it in GitHub Desktop.
Save OliverJAsh/03fa1e4b520ecda3311072adeec4912a to your computer and use it in GitHub Desktop.
async iterable operators (map, filter) using async generators
const getName = async function*() {
yield 'bob';
yield 'baz';
yield 'bar';
};
const getAge = (name: string) => {
const responseJson = fetch('https://httpbin.org/get')
.then(response => response.json())
// Let's pretend the API is returning an age for us
.then(() => Math.round(Math.random() * 100));
return responseJson;
};
// https://github.com/ReactiveX/IxJS/blob/3218613193258c4d817a4dcbf2423df0e070d516/src/asynciterable/operators/filter.ts
const filter = async function*<T, T2>(
source: AsyncIterable<T>,
predicate: (item: T, index: number) => boolean,
) {
let i = 0;
for await (const item of source) {
if (predicate(item, i++)) {
yield item;
}
}
};
// https://github.com/ReactiveX/IxJS/blob/3218613193258c4d817a4dcbf2423df0e070d516/src/asynciterable/operators/map.ts
const map = async function*<T, T2>(
source: AsyncIterable<T>,
selector: (item: T, index: number) => T2 | Promise<T2>,
) {
let i = 0;
for await (const item of source) {
const result = await selector(item, i++);
yield result;
}
};
const stringAsyncIterable = map(
filter(getName(), name => name === 'bob'),
name => getAge(name).then(age => `${name}'s current age: ${age}`),
);
(async () => {
for await (let value of stringAsyncIterable) {
console.log(value);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment