Fix tweet truncation issue by truncating at complete sentences #388
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Original Code (Before Fix)
The original code was truncating tweets incorrectly, often cutting them off mid-sentence. The logic did not ensure that tweets ended at a complete sentence or whitespace, leading to awkward, incomplete posts.
Problematic Section
const contentLength = 240;
let content = slice.slice(0, contentLength);
// if its bigger than 280, delete the last line
if (content.length > 280) {
content = content.slice(0, content.lastIndexOf("\n"));
}
if (content.length > contentLength) {
// slice at the last period
content = content.slice(0, content.lastIndexOf("."));
}
// if it's still too long, get the period before the last period
if (content.length > contentLength) {
content = content.slice(0, content.lastIndexOf("."));
}
Issues:
Updated Code (After Fix)
We introduced a new helper function, truncateToCompleteSentence, to properly truncate the text. This function ensures that:
Fixed Section
const MAX_TWEET_LENGTH = 280;
/**
Truncate text to fit within the Twitter character limit, ensuring it ends at a complete sentence.
*/
function truncateToCompleteSentence(text: string): string {
if (text.length <= MAX_TWEET_LENGTH) {
return text;
}
// Attempt to truncate at the last period within the limit
const truncatedAtPeriod = text.slice(0, text.lastIndexOf(".", MAX_TWEET_LENGTH) + 1);
if (truncatedAtPeriod.trim().length > 0) {
return truncatedAtPeriod.trim();
}
// If no period is found, truncate to the nearest whitespace
const truncatedAtSpace = text.slice(0, text.lastIndexOf(" ", MAX_TWEET_LENGTH));
if (truncatedAtSpace.trim().length > 0) {
return truncatedAtSpace.trim() + "...";
}
// Fallback: Hard truncate and add ellipsis
return text.slice(0, MAX_TWEET_LENGTH - 3).trim() + "...";
}
// Inside the generateNewTweet function:
const formattedTweet = newTweetContent.replaceAll(/\n/g, "\n").trim();
const content = truncateToCompleteSentence(formattedTweet);
Key Improvements