All files / string splitByCase.ts

100% Statements 17/17
100% Branches 6/6
100% Functions 2/2
100% Lines 17/17

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                    89x 1x     88x 1x     87x 87x     11x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x      
import { isString } from '../is'
 
/**
 * split string into word groups
 *
 * @param text text to split
 * @param delimiter split regexp, default to /[\s\-_/.]/
 * @returns word groups
 */
export function splitByCase(text: unknown, delimiter?: RegExp): string[] {
  if (!isString(text)) {
    return []
  }
 
  if (delimiter) {
    return text.split(delimiter).filter(Boolean)
  }
 
  delimiter = /[\s\-_/.]/
  return text.replace(/([a-z])([A-Z])/g, '$1-$2').split(delimiter).filter(Boolean)
}
 
if (import.meta.vitest) {
  const { test, expect } = import.meta.vitest
 
  test('splitByCase', () => {
    expect(splitByCase(1)).toEqual([])
    expect(splitByCase('1-2', /-/)).toEqual(['1', '2'])
 
    expect(splitByCase('useXx')).toEqual(['use', 'Xx'])
    expect(splitByCase('use-xx')).toEqual(['use', 'xx'])
    expect(splitByCase('use xx')).toEqual(['use', 'xx'])
    expect(splitByCase('UseXx')).toEqual(['Use', 'Xx'])
    expect(splitByCase('use_xx')).toEqual(['use', 'xx'])
    expect(splitByCase('Use Xx')).toEqual(['Use', 'Xx'])
  })
}