textChunker.js 506 B

1234567891011121314151617
  1. export function chunkText(text, { chunkSize, chunkOverlap }) {
  2. const normalized = String(text ?? "").replace(/\r\n/g, "\n").trim();
  3. if (!normalized) return [];
  4. const chunks = [];
  5. let start = 0;
  6. while (start < normalized.length) {
  7. const end = Math.min(start + chunkSize, normalized.length);
  8. const chunk = normalized.slice(start, end).trim();
  9. if (chunk) chunks.push(chunk);
  10. if (end >= normalized.length) break;
  11. start = Math.max(0, end - chunkOverlap);
  12. }
  13. return chunks;
  14. }