Skip to content

Commit 51a01d5

Browse files
chore: refactor to add reconstruct function (#10)
1 parent 0f91732 commit 51a01d5

File tree

2 files changed

+11
-12
lines changed

2 files changed

+11
-12
lines changed

src/core/splitters/markdown.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ export class MarkdownSplitter {
2727
})
2828
}
2929

30+
/**
31+
* Appends a chunk to an accumulator string, preserving whitespace
32+
*/
33+
reconstructChunk(accumulator: string, chunk: Chunk): string {
34+
return accumulator + (chunk.leadingWhitespace || '') + chunk.content + (chunk.trailingWhitespace || '')
35+
}
36+
3037
/**
3138
* Default split method - automatically detects and uses the appropriate splitting strategy.
3239
* If the content contains ::page directives, splits by those.

src/core/translators/markdown.ts

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,14 @@ export class MarkdownTranslator {
2424
let response = ''
2525

2626
for (const chunk of chunks) {
27-
response += chunk.leadingWhitespace || ''
28-
2927
if (chunk.shouldTranslate) {
3028
// eslint-disable-next-line no-await-in-loop
3129
const translatedChunk = await this.chatModel.invoke(this.buildMessages({...options, content: chunk.content}))
3230

33-
response += translatedChunk.content as string
31+
response = this.splitter.reconstructChunk(response, {...chunk, content: translatedChunk.content as string})
3432
} else {
35-
response += chunk.content
33+
response = this.splitter.reconstructChunk(response, chunk)
3634
}
37-
38-
response += chunk.trailingWhitespace || ''
3935
}
4036

4137
return response
@@ -49,9 +45,7 @@ export class MarkdownTranslator {
4945
const chunks = await this.splitter.split(options.content)
5046

5147
for (const chunk of chunks) {
52-
if (chunk.leadingWhitespace) {
53-
yield chunk.leadingWhitespace
54-
}
48+
yield chunk.leadingWhitespace || ''
5549

5650
if (chunk.shouldTranslate) {
5751
// eslint-disable-next-line no-await-in-loop
@@ -65,9 +59,7 @@ export class MarkdownTranslator {
6559
yield chunk.content
6660
}
6761

68-
if (chunk.trailingWhitespace) {
69-
yield chunk.trailingWhitespace
70-
}
62+
yield chunk.trailingWhitespace || ''
7163
}
7264
}
7365

0 commit comments

Comments
 (0)