forked from reiver/go-stringcase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamel.go
More file actions
68 lines (60 loc) · 1.57 KB
/
Copy pathcamel.go
File metadata and controls
68 lines (60 loc) · 1.57 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package stringcase
import "bufio"
import "github.com/reiver/go-whitespace"
import "strings"
import "unicode"
// ToCamelCase converts the string to "camelCase" and returns it.
func ToCamelCase(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.
//
first := true
prev := ' '
result := strings.Map(
func(r rune) rune {
if first && (whitespace.IsWhitespace(prev) || '_' == prev || '-' == prev) {
first = false
prev = r
return unicode.ToLower(r)
} else if !first && (whitespace.IsWhitespace(prev) || '_' == prev || '-' == prev) {
prev = r
return unicode.ToTitle(r)
} else if whitespace.IsWhitespace(r) || '_' == r || '-' == r {
prev = r
return -1
} else {
prev = r
return unicode.ToLower(r)
}
},
s)
// Return
return result
}
// FromCamelCase converts the "camelCase" string to a spaced string "camel Case"
// and returns it.
func FromCamelCase(s string) string {
scanner := bufio.NewScanner(strings.NewReader(s))
scanner.Split(bufio.ScanRunes)
prevIsLowercase := false
result := ""
for scanner.Scan() {
r := scanner.Text()
if r == strings.ToLower(r) {
prevIsLowercase = true
} else if r == strings.ToUpper(r) {
if prevIsLowercase {
result += " "
}
prevIsLowercase = false
}
result += r
}
// Return
return result
}