Adjust string{Camel, Pascal}Case (#1256)
This commit is contained in:
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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('');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user