Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Created April 21, 2020 22:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericelliott/b18a167adb8d4c40334246890975aaf7 to your computer and use it in GitHub Desktop.
Save ericelliott/b18a167adb8d4c40334246890975aaf7 to your computer and use it in GitHub Desktop.
for-await-of-transducers
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);
function map(f) {
return async function*(values) {
for await (const x of values) {
yield f(x);
}
};
}
function filter(f) {
return async function*(values) {
for await (const x of values) {
if (f(x)) yield x;
}
};
}
const double = x => x * 2;
const isEven = x => x % 2 === 0;
const doubleEvens = compose(
filter(isEven),
map(double)
);
async function* source() {
let n = 1;
while (true) {
//eslint-disable-next-line
yield await new Promise(resolve => setTimeout(() => resolve(n++), 100));
}
}
async function go() {
const iter = doubleEvens(source());
const limit = 5;
let counter = 0;
while (counter < limit) {
const { value } = await iter.next();
console.log(value);
counter++;
}
}
go();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment