All files / string/src truncate.ts

100% Statements 9/9
100% Branches 8/8
100% Functions 3/3
100% Lines 9/9

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521x                                                                     13x 1x 13x 13x 1x     12x         12x   12x    
import { splice } from "./splice";
 
/**
 * Truncates a string to a maximum length.
 *
 * `suffix` length does not influence `maxLength`.
 *
 * If `separator` is provided, it will look for the closest `separator` to truncate to
 *
 * @example
 * Truncate to 3 characters
 * ```ts
 * const truncateTo3 = truncate(3);
 * const s = truncateTo3("12345");
 * console.log(s); // '123'
 * ```
 *
 * @example
 * Truncate to 3 characters, and add `"..."` suffix
 * ```ts
 * const truncateTo3WithSuffix = truncate(3, '...');
 * const s = truncateTo3WithSuffix("12345");
 * console.log(s); // '123...'
 * ```
 *
 * @example
 * Truncate to the closest space (`" "`) up to 9 characters
 * ```ts
 * const truncateTo9AtSpace = truncate(9, "", " ");
 * const s = truncateTo9AtSpace("123 45 6 789");
 * console.log(s); // '123 45 6'
 * ```
 *
 * @returns the truncated String
 */
export const truncate =
  (maxLength: number, suffix = "", separator = "") =>
  (str: string, length = str.length): string => {
    if (length < maxLength) {
      return str;
    }
 
    const lastSeparatorIndex = str
      .slice(0, maxLength + 1)
      .lastIndexOf(separator);
 
    const startIndex =
      separator && lastSeparatorIndex > 0 ? lastSeparatorIndex : maxLength;
 
    return splice(startIndex, length, suffix)(str);
  };