(chunks: string[], overlapChars: number)
| 21 | } |
| 22 | |
| 23 | export function addOverlap(chunks: string[], overlapChars: number): string[] { |
| 24 | if (overlapChars <= 0 || chunks.length <= 1) { |
| 25 | return chunks |
| 26 | } |
| 27 | |
| 28 | const result: string[] = [] |
| 29 | |
| 30 | for (let i = 0; i < chunks.length; i++) { |
| 31 | let chunk = chunks[i] |
| 32 | |
| 33 | if (i > 0) { |
| 34 | const prevChunk = chunks[i - 1] |
| 35 | const overlapLength = Math.min(overlapChars, prevChunk.length) |
| 36 | const overlapText = prevChunk.slice(-overlapLength) |
| 37 | |
| 38 | const wordBoundaryMatch = overlapText.match(/^\s*\S/) |
| 39 | const cleanOverlap = wordBoundaryMatch |
| 40 | ? overlapText.slice(overlapText.indexOf(wordBoundaryMatch[0].trim())) |
| 41 | : overlapText |
| 42 | |
| 43 | if (cleanOverlap.trim()) { |
| 44 | chunk = `${cleanOverlap.trim()} ${chunk}` |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | result.push(chunk) |
| 49 | } |
| 50 | |
| 51 | return result |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * When stepChars is provided (< chunkSizeChars), produces overlapping chunks |
no test coverage detected