Skip to content

Commit 1b3b555

Browse files
authored
fix: use functions in merge (#152)
Switch to using functions declared in module scope instead of fat arrows to maybe avoid extra heap allocations.
1 parent 997b764 commit 1b3b555

File tree

1 file changed

+36
-28
lines changed

1 file changed

+36
-28
lines changed

packages/it-merge/src/index.ts

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,45 @@
4141
*/
4242

4343
import { pushable } from 'it-pushable'
44+
import type { Pushable } from 'it-pushable'
4445

4546
function isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {
4647
return thing[Symbol.asyncIterator] != null
4748
}
4849

50+
async function addAllToPushable <T> (sources: Array<AsyncIterable<T> | Iterable<T>>, output: Pushable<T>): Promise<void> {
51+
try {
52+
await Promise.all(
53+
sources.map(async (source) => {
54+
for await (const item of source) {
55+
output.push(item)
56+
}
57+
})
58+
)
59+
60+
output.end()
61+
} catch (err: any) {
62+
output.end(err)
63+
}
64+
}
65+
66+
async function * mergeSources <T> (sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> {
67+
const output = pushable<T>({
68+
objectMode: true
69+
})
70+
71+
addAllToPushable(sources, output)
72+
.catch(() => {})
73+
74+
yield * output
75+
}
76+
77+
function * mergeSyncSources <T> (syncSources: Array<Iterable<T>>): Generator<T, void, undefined> {
78+
for (const source of syncSources) {
79+
yield * source
80+
}
81+
}
82+
4983
/**
5084
* Treat one or more iterables as a single iterable.
5185
*
@@ -65,36 +99,10 @@ function merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGen
6599

66100
if (syncSources.length === sources.length) {
67101
// all sources are synchronous
68-
return (function * () {
69-
for (const source of syncSources) {
70-
yield * source
71-
}
72-
})()
102+
return mergeSyncSources(syncSources)
73103
}
74104

75-
return (async function * () {
76-
const output = pushable<T>({
77-
objectMode: true
78-
})
79-
80-
void Promise.resolve().then(async () => {
81-
try {
82-
await Promise.all(
83-
sources.map(async (source) => {
84-
for await (const item of source) {
85-
output.push(item)
86-
}
87-
})
88-
)
89-
90-
output.end()
91-
} catch (err: any) {
92-
output.end(err)
93-
}
94-
})
95-
96-
yield * output
97-
})()
105+
return mergeSources(sources)
98106
}
99107

100108
export default merge

0 commit comments

Comments
 (0)