-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
63 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
export const chunkString = (str: string, maxChunkSize = 2000) => { | ||
const chunks = []; | ||
let start = 0; | ||
|
||
while (start < str.length) { | ||
// Determine the end of the chunk | ||
let end = start + maxChunkSize; | ||
|
||
// If end exceeds the string length, adjust it to the end of the string | ||
if (end >= str.length) { | ||
chunks.push(str.slice(start)); | ||
break; | ||
} | ||
|
||
// If the character at the end index is not a whitespace, find the nearest whitespace before it | ||
if (str[end] !== " " && str[end] !== "\n" && str[end] !== "\t") { | ||
const lastWhitespace = str.lastIndexOf(" ", end); | ||
if (lastWhitespace > start) { | ||
end = lastWhitespace; | ||
} else { | ||
// If no whitespace found, use the max chunk size (this case is rare) | ||
end = start + maxChunkSize; | ||
} | ||
} | ||
|
||
// Push the chunk to the array | ||
chunks.push(str.slice(start, end)); | ||
|
||
// Move the start index to the end of the current chunk | ||
start = end + 1; | ||
} | ||
|
||
return chunks; | ||
}; |