Adjust string{Camel, Pascal}Case (#1256)

This commit is contained in:
Jaco
2021-11-29 18:34:04 +02:00
committed by GitHub
parent 80195f6d11
commit 3643c2e306
3 changed files with 21 additions and 11 deletions
@@ -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);
});
+14 -11
View File
@@ -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('');
}
/**