summaryrefslogtreecommitdiff
path: root/strings
diff options
context:
space:
mode:
Diffstat (limited to 'strings')
-rw-r--r--strings/strings.go36
-rw-r--r--strings/strings_test.go15
2 files changed, 51 insertions, 0 deletions
diff --git a/strings/strings.go b/strings/strings.go
index 3ee15c61..8c10865a 100644
--- a/strings/strings.go
+++ b/strings/strings.go
@@ -1,6 +1,7 @@
package strings
import (
+ "regexp"
"sort"
"strings"
)
@@ -45,3 +46,38 @@ func Sort(list []string) []string {
sorted.Sort()
return sorted
}
+
+var (
+ spaces = regexp.MustCompile(`\s+`)
+ nonAlphaNum = regexp.MustCompile(`[^\pL\pN]+`)
+)
+
+// SnakeCase -
+func SnakeCase(in string) string {
+ s := casePrepare(in)
+ return spaces.ReplaceAllString(s, "_")
+}
+
+// KebabCase -
+func KebabCase(in string) string {
+ s := casePrepare(in)
+ return spaces.ReplaceAllString(s, "-")
+}
+
+func casePrepare(in string) string {
+ in = strings.TrimSpace(in)
+ s := strings.ToLower(in)
+ // make sure the first letter remains lower- or upper-cased
+ s = strings.Replace(s, string(s[0]), string(in[0]), 1)
+ s = nonAlphaNum.ReplaceAllString(s, " ")
+ return strings.TrimSpace(s)
+}
+
+// CamelCase -
+func CamelCase(in string) string {
+ in = strings.TrimSpace(in)
+ s := strings.Title(in)
+ // make sure the first letter remains lower- or upper-cased
+ s = strings.Replace(s, string(s[0]), string(in[0]), 1)
+ return nonAlphaNum.ReplaceAllString(s, "")
+}
diff --git a/strings/strings_test.go b/strings/strings_test.go
index f2afb2f5..dfcee552 100644
--- a/strings/strings_test.go
+++ b/strings/strings_test.go
@@ -39,3 +39,18 @@ func TestSort(t *testing.T) {
expected = []string{"18", "42", "45"}
assert.EqualValues(t, expected, Sort(in))
}
+
+func TestCaseFuncs(t *testing.T) {
+ testdata := []struct{ in, s, k, c string }{
+ {" Foo bar ", "Foo_bar", "Foo-bar", "FooBar"},
+ {"foo bar", "foo_bar", "foo-bar", "fooBar"},
+ {" baz\tqux ", "baz_qux", "baz-qux", "bazQux"},
+ {"Hello, World!", "Hello_world", "Hello-world", "HelloWorld"},
+ {"grüne | Straße", "grüne_straße", "grüne-straße", "grüneStraße"},
+ }
+ for _, d := range testdata {
+ assert.Equal(t, d.s, SnakeCase(d.in))
+ assert.Equal(t, d.k, KebabCase(d.in))
+ assert.Equal(t, d.c, CamelCase(d.in))
+ }
+}