Skip to content

Commit

Permalink
Merge pull request #64 from ComponentDriven/norbert/fix-startcase
Browse files Browse the repository at this point in the history
Improve the startcase implementation to mimick lodash's version more closely
  • Loading branch information
ndelangen authored Feb 16, 2023
2 parents 6f29d0c + 1cdb44b commit 223b0c3
Show file tree
Hide file tree
Showing 4 changed files with 677 additions and 654 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@
"eslint-plugin-jest": "^27.1.4",
"expect-type": "^0.14.2",
"jest": "^29.3.1",
"lodash": "^4.17.21",
"@types/lodash": "^4.14.191",
"prettier": "^2.7.1",
"ts-jest": "^29.0.3",
"tsup": "^6.4.0",
Expand Down
29 changes: 21 additions & 8 deletions src/toStartCaseStr.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable import/no-extraneous-dependencies */
import startCase from 'lodash/startCase';
import { toStartCaseStr } from './toStartCaseStr';

test.each([
['snake_case', 'Snake Case'],
['AAAaaaAAAaaa', 'AA Aaaa AA Aaaa'],
['kebab-case', 'Kebab Case'],
['camelCase', 'Camel Case'],
['camelCase1', 'Camel Case 1'],
['camelCase1a', 'Camel Case 1a'],
['camelCase1A', 'Camel Case 1A'],
['camelCase1A2', 'Camel Case 1A 2'],
['camelCase1A2b', 'Camel Case 1A 2b'],
['camelCase1A2B', 'Camel Case 1A 2B'],
['camelCase1A2B3', 'Camel Case 1A 2B 3'],
['camelCase1a', 'Camel Case 1 A'],
['camelCase1A', 'Camel Case 1 A'],
['camelCase1A2', 'Camel Case 1 A 2'],
['camelCase1A2b', 'Camel Case 1 A 2 B'],
['camelCase1A2B', 'Camel Case 1 A 2 B'],
['camelCase1A2B3', 'Camel Case 1 A 2 B 3'],
['__FOOBAR__', 'FOOBAR'],
['__FOO_BAR__', 'FOO BAR'],
['__FOO__BAR__', 'FOO BAR'],
[' FOO BAR', 'FOO BAR'],
['1. Fooo', '1. Fooo'],
['1. Fooo', '1 Fooo'],
['ZIndex', 'Z Index'],
])('%s', (str, expected) => {
expect(toStartCaseStr(str)).toBe(expected);
const outcome = toStartCaseStr(str);
const fromLodash = startCase(str);

expect({ outcome, fromLodash }).toEqual({
outcome: expected,
fromLodash,
});
expect(outcome).toEqual(fromLodash);
});
6 changes: 5 additions & 1 deletion src/toStartCaseStr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ export function toStartCaseStr(str: string) {
return str
.replace(/_/g, ' ')
.replace(/-/g, ' ')
.replace(/\./g, ' ')
.replace(/([^\n])([A-Z])([a-z])/g, (str2, $1, $2, $3) => `${$1} ${$2}${$3}`)
.replace(/([a-z])([A-Z])/g, (str2, $1, $2) => `${$1} ${$2}`)
.replace(/([a-z])([0-9])/gi, (str2, $1, $2) => `${$1} ${$2}`)
.replace(/(\s|^)(\w)/g, (str2, $1, $2) => $1 + $2.toUpperCase())
.replace(/([0-9])([a-z])/gi, (str2, $1, $2) => `${$1} ${$2}`)
.replace(/(\s|^)(\w)/g, (str2, $1, $2) => `${$1}${$2.toUpperCase()}`)
.replace(/ +/g, ' ')
.trim();
}
Loading

0 comments on commit 223b0c3

Please sign in to comment.