Skip to content

Commit

Permalink
Merge pull request #77 from marnusw/filterTransform
Browse files Browse the repository at this point in the history
Implement filter as a Transform stream to fix piping
  • Loading branch information
gsantiago authored Jan 2, 2022
2 parents 0e71b06 + 2f70ec5 commit 65318e9
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 9 deletions.
13 changes: 6 additions & 7 deletions src/filter.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Node } from '.'
import { createDuplex } from './utils'
import { Transform } from 'stream'

export const filter = (callback: (node: Node) => boolean) =>
createDuplex({
write(chunk, _encoding, next) {
if (callback(chunk)) {
this.push(chunk)
}
next()
new Transform({
objectMode: true,
autoDestroy: false,
transform: function transform(chunk, _encoding, next) {
callback(chunk) ? next(null, chunk) : next()
}
})
8 changes: 8 additions & 0 deletions test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,11 @@ export const pipeline = (stream: Readable): Promise<NodeList> =>
stream.on('error', reject)
stream.on('finish', () => resolve(buffer))
})

export const streamToString = (stream: Readable): Promise<string> =>
new Promise((resolve, reject) => {
let buffer = ''
stream.on('data', (chunk: string) => buffer += chunk)
stream.on('error', reject)
stream.on('finish', () => resolve(buffer))
})
41 changes: 39 additions & 2 deletions test/filter.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createStreamFromString, pipeline } from '../test-utils'
import { filter, parse } from '../src'
import { createStreamFromString, pipeline, streamToString } from '../test-utils'
import { filter, parse, stringify } from '../src'

test('filter nodes', async () => {
const stream = createStreamFromString(`
Expand Down Expand Up @@ -44,3 +44,40 @@ Welcome to the Planet.\n`)
]
`)
})

test('filter nodes and forward to the next stream', async () => {
const stream = createStreamFromString(`
1
02:12:34,647 --> 02:12:35,489
Hi.
2
02:12:36,415 --> 02:12:37,758
𝅘𝅥𝅮 Some Music 𝅘𝅥𝅮
3
02:12:38,584 --> 02:12:40,120
Welcome to the Planet.\n`)

const data = await streamToString(
stream
.pipe(parse())
.pipe(
filter(node => !(node.type === 'cue' && node.data.text.includes('𝅘𝅥𝅮')))
)
.pipe(stringify({ format: 'WebVTT' }))
)

expect(data).toMatchInlineSnapshot(`
"WEBVTT
1
02:12:34.647 --> 02:12:35.489
Hi.
2
02:12:38.584 --> 02:12:40.120
Welcome to the Planet.
"
`)
})

0 comments on commit 65318e9

Please sign in to comment.