示例工程 43-project-local-knowledge-base

43-project-local-knowledge-base/app/.tsc/shared/chunk.js

javascript · 0.8 KB

export function chunkText(text, max = 360, overlap = 60) {
    const clean = text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "");
    const chunks = [];
    let start = 0;
    while (start < clean.length) {
        let end = Math.min(clean.length, start + max);
        if (end < clean.length) {
            const window = clean.slice(start, end);
            const cut = Math.max(window.lastIndexOf("\n\n"), window.lastIndexOf("。"), window.lastIndexOf(";"));
            if (cut > max * 0.4)
                end = start + cut + 1;
        }
        const body = clean.slice(start, end).trim();
        if (body)
            chunks.push(body);
        if (end >= clean.length)
            break;
        start = Math.max(start + 1, end - overlap);
    }
    return chunks;
}
//# sourceMappingURL=chunk.js.map