792
*/
793
export function rcut(text: string, n: number, suffix = ''): string {
795
>
796
>
if (trimmed.length <= n) {
797
>
return trimmed;
798
>
}
799
>
800
>
const re = /\b/g;
801
>
let lastGoodBreak = 0;
802
>
let foundBoundaryAfterN = false;
803
>
while (re.test(trimmed)) {
804
>
if (re.lastIndex > n) {
805
>
foundBoundaryAfterN = true;
806
>
break;
807
>
}
808
>
lastGoodBreak = re.lastIndex;
809
>
re.lastIndex += 1;
810
>
}
811
>
812
>
// If no boundary was found after n, return the full trimmed string
813
>
// (there's no good place to cut)
814
>
if (!foundBoundaryAfterN) {
815
>
return trimmed;
816
>
}
817
>
818
>
// If the only boundary <= n is at position 0 (start of string),
819
>
// cutting there gives empty string, so just return the suffix
820
>
if (lastGoodBreak === 0) {
821
>
return suffix;
822
>
}
823
>
824
>
const result = trimmed.substring(0, lastGoodBreak).trimEnd();
825
>
826
>
// If trimEnd removed more than half of what we cut (meaning we cut
827
>
// mostly through whitespace), return the full string instead
828
>
if (result.length < lastGoodBreak / 2) {
829
>
return trimmed;
830
>
}
831
>
832
>
return result + suffix;
833
>
}
834
835
// Defacto standard: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html