Skip to content

Commit

Permalink
Function to convert to upper snake case
Browse files Browse the repository at this point in the history
Closes #6
  • Loading branch information
stoewer committed Feb 26, 2020
1 parent d9b4e2d commit e8fc715
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
47 changes: 46 additions & 1 deletion snake.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import (

// SnakeCase converts a string into snake case.
func SnakeCase(s string) string {
return lowerDelimiterCase(s, '_')
return delimiterCase(s, '_', false)
}

// UpperSnakeCase converts a string into snake case with capital letters.
func UpperSnakeCase(s string) string {
return delimiterCase(s, '_', true)
}

// lowerDelimiterCase converts a string into snake_case or kebab-case depending on
Expand Down Expand Up @@ -46,3 +51,43 @@ func lowerDelimiterCase(s string, delimiter rune) string {

return string(buffer)
}

// delimiterCase converts a string into snake_case or kebab-case depending on the delimiter passed
// as second argument. When upperCase is true the result will be UPPER_SNAKE_CASE or UPPER-KEBAB-CASE.
func delimiterCase(s string, delimiter rune, upperCase bool) string {
s = strings.TrimSpace(s)
buffer := make([]rune, 0, len(s)+3)

adjustCase := toLower
if upperCase {
adjustCase = toUpper
}

var prev rune
var curr rune
for _, next := range s {
if isDelimiter(curr) {
if !isDelimiter(prev) {
buffer = append(buffer, delimiter)
}
} else if isUpper(curr) {
if isLower(prev) || (isUpper(prev) && isLower(next)) {
buffer = append(buffer, delimiter)
}
buffer = append(buffer, adjustCase(curr))
} else if curr != 0 {
buffer = append(buffer, adjustCase(curr))
}
prev = curr
curr = next
}

if len(s) > 0 {
if isUpper(curr) && isLower(prev) && prev != 0 {
buffer = append(buffer, delimiter)
}
buffer = append(buffer, adjustCase(curr))
}

return string(buffer)
}
23 changes: 23 additions & 0 deletions snake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,26 @@ func TestSnakeCase(t *testing.T) {
assert.Equal(t, snake, converted)
}
}

func TestUpperSnakeCase(t *testing.T) {
data := map[string]string{
"": "",
"F": "F",
"Foo": "FOO",
"FooB": "FOO_B",
"FooID": "FOO_ID",
" FooBar\t": "FOO_BAR",
"HTTPStatusCode": "HTTP_STATUS_CODE",
"ParseURL.DoParse": "PARSE_URL.DO_PARSE",
"Convert Space": "CONVERT_SPACE",
"Convert-dash": "CONVERT_DASH",
"Skip___MultipleUnderscores": "SKIP_MULTIPLE_UNDERSCORES",
"Skip MultipleSpaces": "SKIP_MULTIPLE_SPACES",
"Skip---MultipleDashes": "SKIP_MULTIPLE_DASHES",
}

for camel, snake := range data {
converted := UpperSnakeCase(camel)
assert.Equal(t, snake, converted)
}
}

0 comments on commit e8fc715

Please sign in to comment.