-
Notifications
You must be signed in to change notification settings - Fork 0
/
romaji.go
70 lines (53 loc) · 1.68 KB
/
romaji.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
package wanakana
import (
"regexp"
"strings"
"github.com/deelawn/wanakana/config"
"github.com/deelawn/wanakana/internal/character"
"github.com/deelawn/wanakana/internal/transform"
"github.com/deelawn/wanakana/tree"
)
// IsRomaji returns true if all characters in the string are Romaji or match
// the optional regular expression.
func IsRomaji(input string, regex *regexp.Regexp) bool {
if len(input) == 0 {
return false
}
for _, r := range []rune(input) {
if character.IsRomaji(r) {
// This character is Romaji; keep going.
continue
}
if regex != nil && regex.MatchString(string(r)) {
// This character isn't Romaji but matches the regex; keep going.
continue
}
return false
}
return true
}
// ToRomaji converts input to romaji with the option to uppercase katakana.
func ToRomaji(input string, options config.Options, treeMap *tree.Map) string {
if treeMap == nil {
treeMap = createKanaToRomajiTree(options.Romanization, options.CustomKanaMapping)
}
inputRunes := []rune(input)
hiraganaInput := transform.KatakanaToHiragana(input, treeMap, true, !options.IgnoreLongVowelMark)
tokens := transform.ToKanaToken([]rune(hiraganaInput), treeMap, false)
var result string
for _, token := range tokens {
if options.UppercaseKatakana && IsKatakana(string(inputRunes[token.Start:token.End])) {
token.Value = strings.ToUpper(token.Value)
}
result += token.Value
}
return result
}
func createKanaToRomajiTree(romanization config.Romanization, customMapping config.CustomMapping) *tree.Map {
treeMap := transform.GetKanaToRomajiTreeMap(romanization)
if customMapping != nil {
treeMap = treeMap.Copy()
customMapping.Apply(treeMap)
}
return treeMap
}