Skip to content

Commit 651ba7d

Browse files
authored
Move regexp to outer scope (#87)
1 parent 4f40fee commit 651ba7d

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

index.js

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
'use strict';
22

3+
const UPPERCASE = /[\p{Lu}]/u;
4+
const LOWERCASE = /[\p{Ll}]/u;
5+
const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
6+
const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
7+
const SEPARATORS = /[_.\- ]+/;
8+
9+
const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);
10+
const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');
11+
const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu');
12+
313
const preserveCamelCase = (string, locale) => {
414
let isLastCharLower = false;
515
let isLastCharUpper = false;
@@ -8,13 +18,13 @@ const preserveCamelCase = (string, locale) => {
818
for (let i = 0; i < string.length; i++) {
919
const character = string[i];
1020

11-
if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
21+
if (isLastCharLower && UPPERCASE.test(character)) {
1222
string = string.slice(0, i) + '-' + string.slice(i);
1323
isLastCharLower = false;
1424
isLastLastCharUpper = isLastCharUpper;
1525
isLastCharUpper = true;
1626
i++;
17-
} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
27+
} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
1828
string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
1929
isLastLastCharUpper = isLastCharUpper;
2030
isLastCharUpper = false;
@@ -30,12 +40,17 @@ const preserveCamelCase = (string, locale) => {
3040
};
3141

3242
const preserveConsecutiveUppercase = input => {
33-
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
43+
LEADING_CAPITAL.lastIndex = 0;
44+
45+
return input.replace(LEADING_CAPITAL, m1 => m1.toLowerCase());
3446
};
3547

3648
const postProcess = (input, options) => {
37-
return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale))
38-
.replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
49+
SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
50+
NUMBERS_AND_IDENTIFIER.lastIndex = 0;
51+
52+
return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => identifier.toLocaleUpperCase(options.locale))
53+
.replace(NUMBERS_AND_IDENTIFIER, m => m.toLocaleUpperCase(options.locale));
3954
};
4055

4156
const camelCase = (input, options) => {
@@ -71,7 +86,7 @@ const camelCase = (input, options) => {
7186
input = preserveCamelCase(input, options.locale);
7287
}
7388

74-
input = input.replace(/^[_.\- ]+/, '');
89+
input = input.replace(LEADING_SEPARATORS, '');
7590

7691
if (options.preserveConsecutiveUppercase) {
7792
input = preserveConsecutiveUppercase(input);

0 commit comments

Comments
 (0)