Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(pascal): struggles with camel-cased strings #178

Merged
merged 7 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions benchmarks/string/pascal.bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,10 @@ describe('pascal', () => {
bench('with valid input', () => {
_.pascal('hello world')
})
bench('with camelCase input', () => {
_.pascal('fooBar')
})
bench('with non alphanumerics', () => {
_.pascal('Exobase Starter_flash AND-go')
})
})
1 change: 1 addition & 0 deletions docs/string/pascal.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ import * as _ from 'radashi'

_.pascal('hello world') // => 'HelloWorld'
_.pascal('va va boom') // => 'VaVaBoom'
_.pascal('helloWorld') // => 'HelloWorld'
```
17 changes: 14 additions & 3 deletions src/string/pascal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,23 @@
* ```ts
* pascal('hello world') // => 'HelloWorld'
* pascal('va va boom') // => 'VaVaBoom'
* pascal('helloWorld') // => 'HelloWorld'
* ```
*/
export function pascal(str: string): string {
const parts = str?.split(/[\.\-\s_]/).map(x => x.toLowerCase()) ?? []
if (parts.length === 0) {
if (!str) {
return ''
}
return parts.map(str => str.charAt(0).toUpperCase() + str.slice(1)).join('')

const result = str.replace(
/(?:[^\w\d]|_|\s)+(\w)([A-Z]+)?/g,
(_, firstCharacter, capitalizedLetters) => {
if (capitalizedLetters) {
return firstCharacter.toUpperCase() + capitalizedLetters.toLowerCase()
}
return firstCharacter.toUpperCase()
},
)

return result[0].toUpperCase() + result.substring(1)
}
4 changes: 4 additions & 0 deletions tests/string/pascal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ describe('pascal', () => {
const result = _.pascal(null as any)
expect(result).toBe('')
})
test('converts camelCase to PascalCase', () => {
const result = _.pascal('fooBar')
expect(result).toBe('FooBar')
})
})
Loading