Skip to content

Commit 0ed3d4f

Browse files
authored
feat: enhance SplitCamelWords() (#2)
* feat: enhance SplitCamelWords() * refactor: improve readability of SplitCamelWords function * refactor: combine shouldSplit and b.Len() > 0 condition in SplitCamelWords
1 parent fe5b978 commit 0ed3d4f

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/plugins/utils/strings.go

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,31 @@ func buildSnakeCaseWords(ss []string) string {
5151
}
5252

5353
func SplitCamelWords(s string) []string {
54-
currentWord := new(strings.Builder)
54+
runes := []rune(s)
55+
if len(runes) == 0 {
56+
return nil
57+
}
5558
words := make([]string, 0)
56-
for _, r := range s {
57-
if unicode.IsUpper(r) && currentWord.Len() > 0 {
58-
words = append(words, currentWord.String())
59-
currentWord.Reset()
59+
var b strings.Builder
60+
for i, r := range runes {
61+
if i == 0 {
62+
b.WriteRune(unicode.ToLower(r))
63+
continue
64+
}
65+
prev := runes[i-1]
66+
nextIsLower := i+1 < len(runes) && unicode.IsLower(runes[i+1])
67+
// Check if we're at the start of a new word (lowercase to uppercase, or uppercase sequence ending)
68+
isNewWord := unicode.IsLower(prev) || (unicode.IsUpper(prev) && nextIsLower)
69+
// Split when current char is uppercase and marks a new word boundary
70+
shouldSplit := unicode.IsUpper(r) && isNewWord
71+
if shouldSplit && b.Len() > 0 {
72+
words = append(words, b.String())
73+
b.Reset()
6074
}
61-
currentWord.WriteRune(unicode.ToLower(r))
75+
b.WriteRune(unicode.ToLower(r))
6276
}
63-
if currentWord.Len() > 0 {
64-
words = append(words, currentWord.String())
77+
if b.Len() > 0 {
78+
words = append(words, b.String())
6579
}
6680
return words
6781
}

0 commit comments

Comments
 (0)