forked from reiver/go-stringcase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheader.go
More file actions
47 lines (37 loc) · 1.05 KB
/
header.go
File metadata and controls
47 lines (37 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package stringcase
import "github.com/reiver/go-whitespace"
import "strings"
import "unicode"
// ToHeaderCase converts the string to "Header-Case" and returns it.
func ToHeaderCase(s string) string {
// Here we use a similar hack that the Golang strings.Title() func uses,
// which uses the strings.Map() func but (and this is the hack'y part)
// depends on the interation order of strings.Map().
//
// See: https://golang.org/src/strings/strings.go#L519
//
// Specifically, assumes it iterates from beginning to end.
//
prev := ' '
result := strings.Map(
func(r rune) rune {
if whitespace.IsWhitespace(prev) || '_' == prev || '-' == prev {
prev = r
return unicode.ToTitle(r)
} else if whitespace.IsWhitespace(r) || '_' == r {
prev = r
return '-'
} else {
prev = r
return unicode.ToLower(r)
}
},
s)
// Return
return result
}
// FromHeaderCase converts the "Header-Case" string to a spaced string
// "Header Case" and returns it.
func FromHeaderCase(s string) string {
return strings.Replace(s, "-", " ", -1)
}