Skip to content

Commit 53b3bab

Browse files
committed
refactor: reuse iterators logic
1 parent 75a620f commit 53b3bab

File tree

2 files changed

+17
-18
lines changed

2 files changed

+17
-18
lines changed

src/core.ts

+8-18
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ import {
4747
log,
4848
isString,
4949
isStringLiteral,
50-
bufToString,
5150
getLast,
51+
getLines,
5252
noop,
5353
once,
5454
parseBool,
@@ -601,26 +601,19 @@ export class ProcessPromise extends Promise<ProcessOutput> {
601601

602602
// Async iterator API
603603
async *[Symbol.asyncIterator](): AsyncIterator<string> {
604-
let last: string | undefined
605-
const getLines = (chunk: Buffer | string) => {
606-
const lines = ((last || '') + bufToString(chunk)).split('\n')
607-
last = lines.pop()
608-
return lines
609-
}
604+
const memo: (string | undefined)[] = []
610605

611606
for (const chunk of this._zurk!.store.stdout) {
612-
const lines = getLines(chunk)
613-
for (const line of lines) yield line
607+
yield* getLines(chunk, memo)
614608
}
615609

616610
for await (const chunk of this.stdout[Symbol.asyncIterator]
617611
? this.stdout
618612
: VoidStream.from(this.stdout)) {
619-
const lines = getLines(chunk)
620-
for (const line of lines) yield line
613+
yield* getLines(chunk, memo)
621614
}
622615

623-
if (last) yield last
616+
if (memo[0]) yield memo[0]
624617

625618
if ((await this.exitCode) !== 0) throw this._output
626619
}
@@ -766,16 +759,13 @@ export class ProcessOutput extends Error {
766759
}
767760

768761
*[Symbol.iterator](): Iterator<string> {
769-
let buffer = ''
762+
const memo: (string | undefined)[] = []
770763

771764
for (const chunk of this._dto.store.stdall) {
772-
buffer += chunk.toString()
773-
const lines = buffer.split(/\r?\n/)
774-
buffer = lines.pop() ?? ''
775-
yield* lines
765+
yield* getLines(chunk, memo)
776766
}
777767

778-
if (buffer) yield buffer
768+
if (memo[0]) yield memo[0]
779769
}
780770

781771
static getExitMessage = formatExitMessage

src/util.ts

+9
Original file line numberDiff line numberDiff line change
@@ -383,3 +383,12 @@ export const toCamelCase = (str: string) =>
383383

384384
export const parseBool = (v: string): boolean | string =>
385385
({ true: true, false: false })[v] ?? v
386+
387+
export const getLines = (
388+
chunk: Buffer | string,
389+
next: (string | undefined)[]
390+
) => {
391+
const lines = ((next.pop() || '') + bufToString(chunk)).split(/\r?\n/)
392+
next.push(lines.pop())
393+
return lines
394+
}

0 commit comments

Comments
 (0)