All files / string truncate.ts

100% Statements 8/8
100% Branches 5/5
100% Functions 3/3
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 301x     106x                                 8x 8x 2x   6x 6x        
const graphemeSegmenter = new Intl.Segmenter();
 
function graphemes(text: string): string[] {
  return Array.from(graphemeSegmenter.segment(text), (part) => part.segment);
}
 
/**
 * Shortens a string to a maximum length, with an ellipsis when it is cut. An emoji or an accented letter
 * counts as one character and is never split.
 *
 * @param input - The string to shorten.
 * @param maxLength - The largest length of the result, ellipsis included.
 * @param ellipsis - The text appended when the string is cut. Defaults to `'…'`.
 * @returns The string itself when it fits, the cut string with its ellipsis otherwise.
 * @example
 * truncate('Engine room temperature', 12); // 'Engine room…'
 * truncate('Short', 12); // 'Short'
 * truncate('Engine room temperature', 12, '...'); // 'Engine ro...'
 */
export function truncate(input: string, maxLength: number, ellipsis = '…'): string {
  const characters = graphemes(input);
  if (characters.length <= maxLength) {
    return input;
  }
  const ellipsisCharacters = graphemes(ellipsis);
  return ellipsisCharacters.length >= maxLength
    ? ellipsisCharacters.slice(0, maxLength).join('')
    : characters.slice(0, maxLength - ellipsisCharacters.length).join('') + ellipsis;
}