export class TextTrimmer {
private static readonly ELLIPSIS = '...';
static trim(text: string, maxChars: number): string {
if (maxChars <= 0) {
throw new Error('maxChars must be greater than 0');
}
if (text.length <= maxChars) {
return text;
}
const availableChars = maxChars - TextTrimmer.ELLIPSIS.length;
if (availableChars <= 0) {
return TextTrimmer.ELLIPSIS.substring(0, maxChars);
}
return text.substring(0, availableChars) + TextTrimmer.ELLIPSIS;
}
static trimAtWordBoundary(text: string, maxChars: number): string {
if (maxChars <= 0) {
throw new Error('maxChars must be greater than 0');
}
if (text.length <= maxChars) {
return text;
}
const availableChars = maxChars - TextTrimmer.ELLIPSIS.length;
if (availableChars <= 0) {
return TextTrimmer.ELLIPSIS.substring(0, maxChars);
}
// Find the last word boundary within the available characters
const truncated = text.substring(0, availableChars);
const lastSpaceIndex = truncated.lastIndexOf(' ');
if (lastSpaceIndex > 0) {
return truncated.substring(0, lastSpaceIndex) + TextTrimmer.ELLIPSIS;
}
// If no space found, fall back to character truncation
return truncated + TextTrimmer.ELLIPSIS;
}
}