Skip to content

Instantly share code, notes, and snippets.

@twfarland
Created August 1, 2020 01:28
Show Gist options
  • Save twfarland/a1c162e65151debd285eaf03ac6bdeb9 to your computer and use it in GitHub Desktop.
Save twfarland/a1c162e65151debd285eaf03ac6bdeb9 to your computer and use it in GitHub Desktop.
async function* seconds() {
let i = 0
while (i < 10) {
await new Promise(resolve => setTimeout(resolve, 1000))
i++
yield i
}
}
function map(f, gen) {
return async function* () {
for await (let value of gen) {
yield f(value)
}
}
}
function filter(f, gen) {
return async function* () {
for await (let value of gen) {
if (f(value)) { yield value }
}
}
}
function fold(f, seed, gen) {
return async function* () {
let acc = seed
for await (let value of gen) {
acc = f(value, acc)
yield acc
}
}
}
const tens = map(seconds(), n => n * 10)
const main = async () => {
for await (let x of tens()) {
console.log(x)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment