From 0677fbb2616241d25a744b061e32809f4cb8ae1d Mon Sep 17 00:00:00 2001 From: Antonio Greco <20005+agreco@users.noreply.github.com> Date: Wed, 30 Jun 2021 16:19:35 +0100 Subject: [PATCH] utils-snake-casing: Initial snakeCase utility * Add initial utility method for snake casing strings --- src/snakeCase.ts | 8 ++++++++ test/snakeCase.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/snakeCase.ts create mode 100644 test/snakeCase.test.ts diff --git a/src/snakeCase.ts b/src/snakeCase.ts new file mode 100644 index 0000000..cb3d213 --- /dev/null +++ b/src/snakeCase.ts @@ -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; diff --git a/test/snakeCase.test.ts b/test/snakeCase.test.ts new file mode 100644 index 0000000..63d46fb --- /dev/null +++ b/test/snakeCase.test.ts @@ -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); +});