camelCase with mixed uppercase/numbers (#1260)

* camelCase with mixed uppercase/numbers

* consequtive capitals

* CHANGELOG

* CHANGELOG
This commit is contained in:
Jaco
2021-12-01 09:21:31 +02:00
committed by GitHub
parent cf370febf0
commit bdd2bcf236
3 changed files with 40 additions and 10 deletions
+20 -2
View File
@@ -33,8 +33,8 @@ const randomWords = arrayRange(256).map((): [string] => {
describe('stringCamelCase', (): void => {
it('works correctly', (): void => {
expect(
stringCamelCase('Snake_case-...Something spaced')
).toBe('snakeCaseSomethingSpaced');
stringCamelCase('Snake_case-...SomethingSomething spaced')
).toBe('snakeCaseSomethingSomethingSpaced');
});
it('works correctly for String (class', (): void => {
@@ -47,6 +47,24 @@ describe('stringCamelCase', (): void => {
expect(
stringCamelCase('DEDUP_KEY_PREFIX')
).toEqual('dedupKeyPrefix');
expect(
stringCamelCase('SOMETHING')
).toEqual('something');
});
it('adjusts all-uppercase + digits', (): void => {
expect(
stringCamelCase('SS58 PreFIX')
).toEqual('ss58Prefix');
expect(
stringCamelCase('SS58Prefix')
).toEqual('ss58Prefix');
expect(
stringCamelCase('UUID64')
).toEqual('uuid64');
expect(
stringCamelCase('BLAKE2B')
).toEqual('blake2B');
});
it('adjusts with leading _', (): void => {
+9 -8
View File
@@ -10,23 +10,24 @@ import type { AnyString } from '../types';
// a 10+x improvement over the original camelcase npm package (at running)
//
// original: 20.88 μs/op
// this: 1.75 μs/op
// this: 1.91 μ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 all seperators (including consequtive) with spaces
.replace(/[-_., ]+/g, ' ')
// we don't want leading or trailing spaces
.trim()
// all consequtive capitals are changed to lowercase
.replace(/[A-Z]{2,}/g, (w) => w.toLowerCase())
// split into words
.split(' ')
.map((w, i) =>
fn(w[0], i) + (
w.toUpperCase() === w
? w.slice(1).toLowerCase()
: w.slice(1)
)
)
// apply the function to the first letter, the rest as-is
.map((w, i) => fn(w[0], i) + w.slice(1))
// combine into a single word
.join('');
}