@@ -39,3 +39,43 @@ export function initials(name: Maybe<string>): Optional<string> {
3939
4040 return parts . map ( ( p ) => p . toUpperCase ( ) ) . join ( '' ) ;
4141}
42+
43+ /**
44+ * There are cases where important information is at the end of the string and truncating the end isn't helpful.
45+ * This function solves that.
46+ *
47+ * @license https://github.com/kahwee/truncate-middle#license
48+ * @param str - String to be truncated
49+ * @param frontLen - Number of characters to be remained in front
50+ * @param backLen - Number of characters to be remained at the back
51+ * @param truncateStr - String that replaces the truncated portion
52+ * @returns Truncated string. Defaults to '…' if unspecified
53+ */
54+ export function truncateMiddle (
55+ str : Maybe < string > ,
56+ frontLen : number = 0 ,
57+ backLen : number = 0 ,
58+ truncateStr : string = '…' ,
59+ ) : string {
60+ if ( str == undefined ) return '' ;
61+
62+ const strLen = str . length ;
63+ // Round to nearest integer instead of floor to fix decimal parameter test
64+ const frontLength = Math . round ( frontLen ) ;
65+ const backLength = Math . round ( backLen ) ;
66+
67+ if (
68+ ( frontLength === 0 && backLength === 0 ) ||
69+ frontLength >= strLen ||
70+ backLength >= strLen ||
71+ frontLength + backLength >= strLen
72+ ) {
73+ return str ;
74+ } else if ( backLength === 0 ) {
75+ return str . slice ( 0 , frontLength ) + truncateStr ;
76+ } else {
77+ return (
78+ str . slice ( 0 , frontLength ) + truncateStr + str . slice ( strLen - backLength )
79+ ) ;
80+ }
81+ }
0 commit comments