Skip to content

Commit 18c6292

Browse files
committed
perf: improve split string performance
1 parent c0fb1f5 commit 18c6292

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/utils.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,23 @@ export function capitalise(text: string) {
22
return text[0].toUpperCase() + text.slice(1)
33
}
44

5+
const UC_RE = /[A-Z]/
56
export function splitStringByCase(text: string) {
6-
return capitalise(
7-
text
8-
.replace(/[A-Z]+[a-z]/g, h =>
9-
h.length > 2
10-
? h.slice(0, -2) + ' ' + capitalise(h.slice(-2).toLowerCase())
11-
: Array(h).join(' ')
12-
)
13-
.replace(/[a-z][A-Z]+/g, h => `${h[0]} ${h.slice(1)}`)
14-
)
7+
let output = ''
8+
let index = 0
9+
for (const char of text) {
10+
const lastChar = index ? text[index - 1] : ''
11+
const nextChar = text[index + 1]
12+
if (
13+
UC_RE.test(char) &&
14+
(!UC_RE.test(lastChar) || (nextChar && !UC_RE.test(nextChar)))
15+
) {
16+
output += ' '
17+
}
18+
output += char
19+
index++
20+
}
21+
return capitalise(output)
1522
}
1623

1724
export function inArray<A>(items: A | A[]) {

0 commit comments

Comments
 (0)