forked from glrodasz/contentr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresolveEndIndex.js
More file actions
36 lines (28 loc) · 1.05 KB
/
resolveEndIndex.js
File metadata and controls
36 lines (28 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { SENTENCE_END_THRESHOLD_PERCENTAGE } from "./config.js";
export function resolveEndIndex(text, startIndex, maxChunkSize) {
const endIndex = Math.min(startIndex + maxChunkSize, text.length);
const chunk = text.slice(startIndex, endIndex);
const sentenceEndIndices = findSentenceEndIndices(chunk);
const nearestEnd = getNearestEndIndex(sentenceEndIndices);
if (isNoSentenceEnd(nearestEnd, chunk)) {
return endIndex;
} else {
const threshold = chunk.length * (SENTENCE_END_THRESHOLD_PERCENTAGE / 100);
return isBeyondThreshold(nearestEnd, threshold)
? startIndex + nearestEnd + 1
: endIndex;
}
}
function findSentenceEndIndices(chunk) {
const sentenceEndChars = [".", "?", "!"];
return sentenceEndChars.map((char) => chunk.lastIndexOf(char));
}
function getNearestEndIndex(indices) {
return Math.max(...indices, -1);
}
function isNoSentenceEnd(nearestEnd, chunk) {
return nearestEnd === -1 || nearestEnd === chunk.length - 1;
}
function isBeyondThreshold(nearestEnd, threshold) {
return nearestEnd > threshold;
}