Frame · dsa / ai-algorithms / 03-sentence-aware-text-chunker.jsJavaScript
Sentence-Aware Text Chunker With Token Window and Overlap
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Sentence-Aware Text Chunker With Token Window and Overlap
Problem: Before embedding documents for retrieval (RAG), long text is split
into chunks. Implement `chunkText(text, maxTokens, overlapTokens)` where a
"token" is approximated by a whitespace-separated word. Rules:
- Sentences end at `.`, `!` or `?`. Chunks are built from whole sentences
and never exceed `maxTokens` tokens.
- A sentence longer than `maxTokens` is hard-split into word windows of
`maxTokens` tokens, each treated as its own sentence.
- Each new chunk starts with the trailing whole sentences of the previous
chunk whose total size is at most `overlapTokens` (context carry-over),
as long as the next sentence still fits.
Return the chunks as strings (sentences joined by a single space).
Constraints:
- 1 <= maxTokens, 0 <= overlapTokens < maxTokens
- text length <= 10^6 characters
Example:
chunkText("A b c. D e. F g h. I j.", 5, 2)
-> ["A b c. D e.", "D e. F g h.", "I j."]
Approach: Split into sentences with a regex, pre-split oversized ones, then
greedily pack sentences into the current chunk. When the next sentence does
not fit, emit the chunk and seed the next one by walking backwards over the
emitted sentences while they fit in the overlap budget. Time O(n) in the
number of words (overlap walks are bounded by overlapTokens), space O(n).
@param {string} text
@param {number} maxTokens
@param {number} overlapTokens
@returns {string[]}