Skip to content

Instantly share code, notes, and snippets.

@ErickWendel
Created July 8, 2022 15:01
Show Gist options
  • Save ErickWendel/5980104058402374f68fc8d360fdb637 to your computer and use it in GitHub Desktop.
Save ErickWendel/5980104058402374f68fc8d360fdb637 to your computer and use it in GitHub Desktop.
// @erickwendel_
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
const take = (limit) => async function* (source) {
let count = 0;
for await (const item of source) {
if (count++ >= limit) break
yield item
}
}
const filter = (fn) => async function* (source) {
for await (const item of source)
if (fn(item)) yield item
}
const map = (fn) => async function* (source) {
for await (const item of source) yield fn(item)
}
const log = _ => async function* (source) {
for await (const item of source) console.log(item)
}
await pipeline(
Readable.from(['🀯', '😬', 'πŸ˜‚', '😳', '😳']),
take(3),
filter(item => item !== '😬'),
map(item => 'emoji: '.concat(item)),
log(),
)
/*
emoji: 🀯
emoji: πŸ˜‚
*/
console.log()
const readable =
Readable.from(['🀯', '😬', 'πŸ˜‚', '😳', '😳'])
.take(3)
.filter(item => item !== '😬')
.map(item => 'emoji: '.concat(item))
await pipeline(
readable,
log()
)
/*
emoji: 🀯
emoji: πŸ˜‚
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment