Last active
March 31, 2020 07:41
-
-
Save OliverJAsh/03fa1e4b520ecda3311072adeec4912a to your computer and use it in GitHub Desktop.
async iterable operators (map, filter) using async generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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