Skip to content

Commit

Permalink
feat: string helpers titleCase and isLetter
Browse files Browse the repository at this point in the history
  • Loading branch information
KiraLT committed Dec 27, 2022
1 parent 0efc6aa commit 749dfc3
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
26 changes: 25 additions & 1 deletion spec/string.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { truncate, extractWords, camelCase, pascalCase } from '../src'
import { truncate, extractWords, camelCase, pascalCase, titleCase, isLetter } from '../src'

describe('truncate', () => {
it('truncates string', () => {
Expand Down Expand Up @@ -37,3 +37,27 @@ describe('pascalCase', () => {
expect(pascalCase('--foo1bar')).toEqual('Foo1Bar')
})
})

describe('isLetter', () => {
it('checks if `a` is letter', () => {
expect(isLetter('a')).toBeTruthy()
})

it('checks if `-` is letter', () => {
expect(isLetter('-')).toBeFalsy()
})

it('checks if `Ž` is letter', () => {
expect(isLetter('Ž')).toBeTruthy()
})

it('checks if `9` is letter', () => {
expect(isLetter('9')).toBeFalsy()
})
})

describe('titleCase', () => {
it('changes string', () => {
expect(titleCase('hello-world FTW,abc999t t')).toEqual('Hello-World Ftw,Abc999T T')
})
})
39 changes: 39 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@ export const octdigits = '01234567'
*/
export const punctuation = '!"#$%&\'()*+,-./:;<=>?@[]^_`{|}~'

/**
* Check if given value contains at least one letter.
*
* @example
* ```
* isLetter('a')
* // true
* isLetter('-')
* // false
* ```
* @category String
*/
export function isLetter(value: string): boolean {
return value.toLowerCase() != value.toUpperCase()
}

/**
* Truncates string
*
Expand Down Expand Up @@ -118,3 +134,26 @@ export function pascalCase(value: string): string {
const parsed = camelCase(value)
return parsed.charAt(0).toUpperCase() + parsed.slice(1)
}

/**
* Convert the first letter in each to word upper case
*
* @example
* ```
* titleCase('hello world');
* // 'Hello World'
* ```
* @category String
*/
export function titleCase(value: string): string {
return value
.split('')
.map((char, index, chars) => {
const prevChar = chars[index - 1]
if (prevChar && isLetter(prevChar)) {
return char.toLowerCase()
}
return char.toUpperCase()
})
.join('')
}

0 comments on commit 749dfc3

Please sign in to comment.