-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtext.go
67 lines (55 loc) · 1.64 KB
/
text.go
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
package humanize
import (
"strings"
"github.com/imbue11235/words"
)
// FuzzyText formats a fuzzy text as a common sentence,
// capitalizing the first letter of the first word, and
// lower-casing the rest
//
// s := humanize.FuzzyText("some_random-sentence")
// fmt.Print(s) => "Some random sentence"
//
func FuzzyText(input string) string {
return FormatFuzzyText(input, func(index int, word string) string {
if index == 0 {
return strings.Title(word)
}
return strings.ToLower(word)
})
}
// FormatFuzzyText extracts words from a fuzzy text and constructs
// a string from the words, using the provided formatter on every
// extracted word.
//
// s:= humanize.FormatFuzzyText("some_random-sentence", strings.ToUpper)
// fmt.Print(s) => "SOME RANDOM SENTENCE"
//
func FormatFuzzyText(input string, formatter interface{}) string {
extractedWords := words.Extract(input)
var sb strings.Builder
for i, word := range extractedWords {
// append a space before every word, but the first
if i != 0 {
sb.WriteString(" ")
}
if formatter == nil {
sb.WriteString(word)
continue
}
sb.WriteString(useFormatter(formatter, i, word))
}
return sb.String()
}
// useFormatter tries to cast the formatter to one of the two function definitions accepted
// and calls it with given parameters. if the casting is unsuccessful, the parameter string value
// is returned
func useFormatter(formatter interface{}, index int, value string) string {
if formatFunc, ok := formatter.(func(int, string) string); ok {
return formatFunc(index, value)
}
if formatFunc, ok := formatter.(func(string) string); ok {
return formatFunc(value)
}
return value
}