Skip to content

Commit

Permalink
utils-snake-casing: Initial snakeCase utility
Browse files Browse the repository at this point in the history
* Add initial utility method for snake casing strings
  • Loading branch information
agreco committed Jun 30, 2021
1 parent 619ec82 commit 0677fbb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/snakeCase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const snakeCase: (val: string) => string = (val: string): string =>
val
.trim()
.toLowerCase()
.replace(/[^a-zA-Z0-9\p{L}]+/gu, '_')
.replace(/(\s_)/g, (match, p1) => p1.trimStart());

export default snakeCase;
22 changes: 22 additions & 0 deletions test/snakeCase.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import snakeCase from '../src/snakeCase';

test.each([
[ 'abc def', 'abc_def'],
[ 'abc-def', 'abc_def'],
[ 'abc_def', 'abc_def'],
[ 'abc!def', 'abc_def'],
[ 'abc@def', 'abc_def'],
[ 'abc%def', 'abc_def'],
[ 'abc^def', 'abc_def'],
[ 'abc&def', 'abc_def'],
[ 'abc*def', 'abc_def'],
[ 'abc(def', 'abc_def'],
[ 'abc)def', 'abc_def'],
[ 'a品cd!e f', 'a品cd_e_f'],
[ 'ն !w**sss', 'ն_w_sss'],
[ '0 a s w', '0_a_s_w'],
[ '0 a 1 w', '0_a_1_w'],
[ '0 a 1 w', '0_a_1_w']
])('it maps the %s object keys entities', (val, expectedVal) => {
expect(snakeCase(val)).toBe(expectedVal);
});

0 comments on commit 0677fbb

Please sign in to comment.