All files convertStringToNameCase.ts

100% Statements 24/24
100% Branches 7/7
100% Functions 9/9
100% Lines 20/20

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 538x 8x 8x 8x 8x 8x                             8x       13x   27x 34x 34x   13x   5x   11x   8x   5x   2x     5x 2x     3x          
import { capitalize } from './capitalize';
import { filter } from './filter';
import { flatMap } from './flatMap';
import { map } from './map';
import { normalizeString } from './normalizeString';
import { pipe } from './pipe';
/**
 * Convert any string to nameCased variant
 * @param str - the string
 * @param to - convert string to 'PascalCase' | 'camelCase' | 'snake_case' | 'kebab-case' | 'Train-Case'
 * @signature
 *    P.convertStringToNameCase(str, to);
 * @example
 *    P.convertStringToNameCase("Super#@! ===-0- ball %%% cup", 'PascalCase') // -> Super0BallCup
 *    P.convertStringToNameCase("Super#@! ===-0- ball %%% cup", 'camelCase') // -> super0BallCup
 *    P.convertStringToNameCase("Super#@! ===-0- ball %%% cup", 'snake_case') // -> super_0_ball_cup
 *    P.convertStringToNameCase("Super#@! ===-0- ball %%% cup", 'kebab-case') // -> super-0-ball-cup
 *    P.convertStringToNameCase("Super#@! ===-0- ball %%% cup", 'Train-Case') // -> Super-0-Ball-Cup
 * @category String
 */
export function convertStringToNameCase(
  str: string,
  to: 'PascalCase' | 'camelCase' | 'snake_case' | 'kebab-case' | 'Train-Case'
): string {
  const result = pipe(
    str.split(' '),
    flatMap(q => q.split(/(?=[A-Z])| |-/)),
    map(w => normalizeString(w)),
    filter(q => !!q)
  );
  switch (to) {
    case 'kebab-case':
      return result.map(c => c.toLowerCase()).join('-');
    case 'PascalCase':
      return result.map(c => capitalize(c.toLowerCase())).join('');
    case 'Train-Case':
      return result.map(c => capitalize(c.toLowerCase())).join('-');
    case 'snake_case':
      return result.map(c => c.toLowerCase()).join('_');
    case 'camelCase':
      return result
        .map((c, index) => {
          // tslint:disable-next-line:no-if-statement
          if (index === 0) {
            return c.toLowerCase();
          }
 
          return capitalize(c.toLowerCase());
        })
        .join('');
  }
}