All files / libs/ext/string/src/lib string.utils.ts

97.46% Statements 77/79
91.66% Branches 11/12
100% Functions 6/6
97.46% Lines 77/79

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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 801x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 4x 4x 1x 1x 5x 5x 1x 1x 1x 1x 4x 4x 4x 4x 175x 175x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 2x 2x 2x 2x 3x 3x 3x 3x 2x 2x 2x  
import { camelCase } from 'lodash-es';
 
export class StringUtils {
  public static camelCase(name: string): string {
    if (!name) {
      return name;
    }
    // Transform to camel case.
    return camelCase(
      // Remove all characters that are not alpha num, replace with a space instead.
      name.replaceAll(/[^a-zA-Z0-9]/gu, ' '),
    );
  }
 
  public static slugify(text: string) {
    return (
      text
        // Convert to a string.
        .toString()
        // Replace accentuated characters by their non accentuated equivalent (é -> e).
        .normalize('NFD')
        // Remove emojies and "weird" characters.
        .replaceAll(/[\u0300-\u036f]/gu, '')
        // Put down to lowercase.
        .toLowerCase()
        // Remove spaces at the beginning and at the end.
        .trim()
        // Replace spaces by dashes.
        .replaceAll(/\s+/gu, '-')
        // Remove non word character, like punctuations or symbols.
        .replaceAll(/[^\w-]+/gu, '')
        // Replace double dashes by dashes.
        .replaceAll(/--+/gu, '-')
    );
  }
 
  public static readonly SLUG_REGEX = /^[a-z0-9-]*$/u;
 
  public static isSlug(text: string): boolean {
    return StringUtils.SLUG_REGEX.exec(text) !== null;
  }
 
  public static isMachineName(text?: string | null): boolean {
    return !!text && !!/^[A-Za-z0-9]*$/u.exec(text);
  }
}
 
// https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
export const generateRandomString = (length: number) => {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*-!%_';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
};
 
/**
 * Appends a number to a base string to generate a name that is not taken yet.
 *
 * @param base - Base name.
 * @param takenNames - Array containing name that already in use.
 */
export const nameGenerator = (base: string, takenNames: string[]) => {
  if (!takenNames.includes(base)) {
    return base;
  }
 
  let i = 2;
  let name = `${base} ${i}`;
 
  while (takenNames.includes(name)) {
    i++;
    name = `${base} ${i}`;
  }
 
  return name;
};