-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.go
98 lines (83 loc) · 2.04 KB
/
translate.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"fmt"
"regexp"
"strings"
"unicode"
)
var pattern = regexp.MustCompile("(?i)(§[0-9a-fklmnor]|\\b)([b-df-hj-np-tv-xz]*[aeiouy])(\\w*)\\b")
func translate(v any) any {
switch t := v.(type) {
case string:
//fmt.Printf("string: %s\n", t)
return translateText(t)
default:
fmt.Printf("WARN: ignoring unsupported type: %v\n", t)
}
return v
}
func translateText(s string) string {
if len(strings.Trim(s, " ")) < 2 {
return s
}
s = regexReplaceAllStringFunc(pattern, s, func(groups []string) string {
word := modifyWord(groups[2], IsUpper(groups[2]+groups[3]))
if len(word+groups[3]) <= len(*prefix)+1 {
return groups[0]
}
return groups[1] + word + groups[3]
})
return s
}
func modifyWord(word string, isUppercase bool) string {
c := rune(word[0])
if unicode.IsLower(c) || c == 'Y' {
return word
}
vowel := word[len(word)-1]
if isUppercase {
return strings.ToUpper(*prefix) + string(vowel)
}
return *prefix + string(unicode.ToLower(rune(vowel)))
}
func regexReplaceAllStringFunc(re *regexp.Regexp, s string, repl func(groups []string) string) string {
var (
result string
lastIndex int
)
for _, match := range re.FindAllStringSubmatchIndex(s, -1) {
var matchStart, matchEnd = match[0], match[1]
result += s[lastIndex:matchStart]
groups := make([]string, 0, len(match)/2)
for i := 0; i < len(match)-1; i += 2 {
var groupStart, groupEnd = match[i], match[i+1]
if groupStart == -1 || groupEnd == -1 {
groups = append(groups, "")
} else {
groups = append(groups, s[groupStart:groupEnd])
}
}
result += repl(groups)
lastIndex = matchEnd
}
result += s[lastIndex:]
return result
}
// IsUpper is from https://stackoverflow.com/a/59293875
func IsUpper(s string) bool {
for _, r := range s {
if !unicode.IsUpper(r) && unicode.IsLetter(r) {
return false
}
}
return true
}
// IsLower is from https://stackoverflow.com/a/59293875
func IsLower(s string) bool {
for _, r := range s {
if !unicode.IsLower(r) && unicode.IsLetter(r) {
return false
}
}
return true
}