Created
April 21, 2020 22:03
-
-
Save ericelliott/b18a167adb8d4c40334246890975aaf7 to your computer and use it in GitHub Desktop.
for-await-of-transducers
This file contains 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 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