Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add string conversion functions #466

Merged
merged 7 commits into from
Jun 27, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,16 @@ func CamelCase(str string) string {

// KebabCase converts string to kebab case.
func KebabCase(str string) string {
return strings.Join(Words(str), "-")
return strings.Join(Map(Words(str), func(item string, index int) string {
return strings.ToLower(item)
}), "-")
}

// SnakeCase converts string to snake case.
func SnakeCase(str string) string {
return strings.Join(Words(str), "_")
return strings.Join(Map(Words(str), func(item string, index int) string {
return strings.ToLower(item)
}), "_")
}

// Words splits string into an array of its words.
Expand All @@ -145,11 +149,17 @@ func Words(str string) []string {
}

// Capitalize converts the first character of string to upper case and the remaining to lower case.
func Capitalize(word string) string {
if len(word) == 0 {
return word
func Capitalize(str string) string {
if len(str) == 0 {
return str
}
runes := []rune(str)
for i, r := range runes {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say, keep it simple

for i, r := range runes {
     r = unicode.ToLower(r)
     if i == 0 {
	r = unicode.ToUpper(r)
     }
     runes[i] = r
}

if i == 0 {
runes[i] = unicode.ToUpper(r)
} else {
runes[i] = unicode.ToLower(r)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code still looks strange to me

There was a function now deprecated that did this https://pkg.go.dev/strings#Title

It had been replaced by https://pkg.go.dev/golang.org/x/text/cases#Title

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your suggested changes.

}
}
runes := []rune(word)
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}