Untitled
unknown
javascript
a year ago
3.7 kB
12
Indexable
function breakSentence(text) {
const maxLength = 300; // Maximum length of each piece
const pieces = [];
let startIndex = 0;
while (startIndex < text.length) {
const remainingText = text.substring(startIndex);
// If the remaining text is shorter than or equal to maxLength, add it to pieces
if (remainingText.length <= maxLength) {
pieces.push(remainingText.trim());
break;
}
// Define the endIndex at the max length
let endIndex = startIndex + maxLength;
let lastBreakIndex = -1;
// Search backward for the last punctuation or space within maxLength
for (let i = endIndex; i > startIndex; i--) {
const char = remainingText[i - startIndex];
if (['.', '!', '?', ',', ';', ':'].includes(char)) {
lastBreakIndex = i; // Found punctuation
break;
}
// Keep track of the last space if no punctuation is found
if (char === ' ') {
lastBreakIndex = i; // Update to last space
}
}
// If no punctuation is found, use the last space
if (lastBreakIndex === -1) {
lastBreakIndex = remainingText.lastIndexOf(' ', maxLength);
// If there's no space, break at the max length
if (lastBreakIndex === -1) {
lastBreakIndex = maxLength;
}
}
// Create a piece from startIndex to the last punctuation/word boundary
let piece = remainingText.substring(0, lastBreakIndex).trim();
// If the piece doesn't end with punctuation, ensure it does
if (!['.', '!', '?', ',', ';', ':'].includes(piece[piece.length - 1])) {
piece += '.'; // Append a period if necessary
}
// Push the trimmed piece to the pieces array
pieces.push(piece);
// Update startIndex to the next part
startIndex += lastBreakIndex;
// Ensure we skip over any punctuation at the start of the next piece
while (startIndex < text.length && ['.', '!', '?', ',', ';', ':'].includes(remainingText[startIndex])) {
startIndex++; // Skip the punctuation
}
// Skip over any leading spaces
while (startIndex < text.length && remainingText[startIndex] === ' ') {
startIndex++;
}
}
return pieces;
}
// Provided text
const exampleText = "Жил да был на свете пёс. Было у него значит 4 сардельки, с которыми он управлялся вот уже 4 час. Очень вкусные они для него оказались. Ему нравятся отварные сардельки домашнего приготовления. Хозяйка умеет делать качественный фарш из дикой утки. Утка добыта добротным охотником в диком лесу. Погода на тот момент была очень не лётная. Добыл он их и принёс домой. Хозяйка быстро управилась с дичью. Вот и сказочке конец, а кто слушал, молодец.";
// Test the function with the provided example and log the pieces count and lengths
const result = breakSentence(exampleText);
console.log(`Original Text: ${exampleText}`);
console.log(`Pieces Count: ${result.length}`);
console.log('Pieces:');
result.forEach((piece, pieceIndex) => {
console.log(` Piece ${pieceIndex + 1} (Length: ${piece.length}): ${piece}`);
});Editor is loading...
Leave a Comment