From 3643c2e3067e837fe3f864cd67569e635c5500f9 Mon Sep 17 00:00:00 2001 From: Jaco Date: Mon, 29 Nov 2021 17:34:04 +0100 Subject: [PATCH] Adjust string{Camel, Pascal}Case (#1256) --- CHANGELOG.md | 1 + packages/util/src/string/camelCase.spec.ts | 6 ++++++ packages/util/src/string/camelCase.ts | 25 ++++++++++++---------- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ef4afa0c..6b25f34e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Changes: - Remove `Buffer` usage in `x-randomvalues` +- Adjust `stringCaleCase` for all-caps parts ## 8.0.2 diff --git a/packages/util/src/string/camelCase.spec.ts b/packages/util/src/string/camelCase.spec.ts index 46a4e3706..8a55abff4 100644 --- a/packages/util/src/string/camelCase.spec.ts +++ b/packages/util/src/string/camelCase.spec.ts @@ -43,5 +43,11 @@ describe('stringCamelCase', (): void => { ).toBe('fooBarBazTestSpacedExtra'); }); + it('adjusts all-uppercase', (): void => { + expect( + stringCamelCase('DEDUP_KEY_PREFIX') + ).toEqual('dedupKeyPrefix'); + }); + performance('stringCamelCase', 64000, randomWords, stringCamelCase); }); diff --git a/packages/util/src/string/camelCase.ts b/packages/util/src/string/camelCase.ts index c9b57e148..68479d710 100644 --- a/packages/util/src/string/camelCase.ts +++ b/packages/util/src/string/camelCase.ts @@ -3,27 +3,30 @@ import type { AnyString } from '../types'; -const RE_WHITE = /[-_., ]+/g; -const RE_WORDS = /(?:^\w|[A-Z]|\b\w)/g; -const RE_JOIN = /\s/g; - // Adapted from https://stackoverflow.com/a/2970667 // -// this is not as optimal as the original (we split into multiple), however -// it does pass the tests (which the original doesn't) and it is still 10+x -// improvement over the original camelcase npm package (at running) +// this is not as optimal as the original asnwer (we split into multiple), +// however it does pass the tests (which the original doesn't) and it is still +// a 10+x improvement over the original camelcase npm package (at running) // // original: 20.88 μs/op -// this: 1.67 μs/op +// this: 1.75 μs/op // // Caveat of this: only Ascii, but acceptable for the intended usecase function converter (fn: (w: string, i: number) => string): (value: AnyString) => string { return (value: AnyString): string => value .toString() - .replace(RE_WHITE, ' ') - .replace(RE_WORDS, fn) - .replace(RE_JOIN, ''); + .replace(/[-_., ]+/g, ' ') + .split(' ') + .map((w, i) => + fn(w[0], i) + ( + w.toUpperCase() === w + ? w.slice(1).toLowerCase() + : w.slice(1) + ) + ) + .join(''); } /**