diff --git a/packages/core/src/utils/case.test.ts b/packages/core/src/utils/case.test.ts new file mode 100644 index 000000000..13b0680be --- /dev/null +++ b/packages/core/src/utils/case.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { pascal } from './case'; + +describe('pascal case testing', () => { + it('should convert to pascal case', () => { + expect(pascal('PascalCase')).toBe('PascalCase'); + expect(pascal('camelCase')).toBe('CamelCase'); + expect(pascal('kebab-case')).toBe('KebabCase'); + expect(pascal('snake_case')).toBe('SnakeCase'); + expect(pascal('point.case')).toBe('PointCase'); + expect(pascal('UPPER_CASE')).toBe('UpperCase'); + expect(pascal('DrUn-k_CaSE')).toBe('DrUnKCaSE'); + }); + + it('should convert to pascal case with underscore', () => { + expect(pascal('_camelCase')).toBe('_CamelCase'); + expect(pascal('_kebab-case')).toBe('_KebabCase'); + }); + + it('should convert to pascal case when more complex input is given', () => { + expect(pascal('camelCase_')).toBe('CamelCase'); + expect(pascal('more complex input')).toBe('MoreComplexInput'); + }); + + it('should handle some casing edge cases', () => { + expect(pascal('foo_bar_API')).toBe('FooBarAPI'); + }); +}); diff --git a/packages/core/src/utils/case.ts b/packages/core/src/utils/case.ts index be56b1f89..f45a492b2 100644 --- a/packages/core/src/utils/case.ts +++ b/packages/core/src/utils/case.ts @@ -43,12 +43,11 @@ const deapostrophe = (s: string) => { const up = String.prototype.toUpperCase; const low = String.prototype.toLowerCase; -const fill = (s: string, fillWith?: string, isDeapostrophe = false) => { - if (fillWith != null) { - s = s.replace(regexps.fill, function (m, next) { - return next ? fillWith + next : ''; - }); - } +const fill = (s: string, fillWith: string, isDeapostrophe = false) => { + s = s.replace(regexps.fill, function (m, next) { + return next ? fillWith + next : ''; + }); + if (isDeapostrophe) { s = deapostrophe(s); } @@ -92,16 +91,13 @@ const lower = (s: string, fillWith: string, isDeapostrophe: boolean) => { export const pascal = (s: string) => { const isStartWithUnderscore = s?.startsWith('_'); - const pascalString = fill( - prep(s, false, true).replace( - regexps.pascal, - (m: string, border: string, letter: string) => { - return up.call(letter); - }, - ), - '', - true, - ); + if (regexps.upper.test(s)) { + s = low.call(s); + } + + const pascalString = (s.match(/[a-zA-Z0-9]+/g) || []) + .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) + .join(''); return isStartWithUnderscore ? `_${pascalString}` : pascalString; }; @@ -122,7 +118,7 @@ export const kebab = (s: string) => { export const upper = ( s: string, - fillWith?: string, + fillWith: string, isDeapostrophe?: boolean, ) => { return fill(