-
Notifications
You must be signed in to change notification settings - Fork 0
/
latinise.go
68 lines (49 loc) · 1.31 KB
/
latinise.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
package latinify
import (
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
//Table unicode mapped table
type Table map[rune]rune
//String convert any unicode souce in a Latin compatible text
func String(source string) (string, error) {
return StringWithTable(source)
}
type removeMark struct{}
func (m removeMark) Contains(r rune) bool {
return unicode.Is(unicode.Mn, r)
}
type mapping func(rune) rune
type mappedTable struct {
mapping
tables []Table
}
func replaceTable(table Table) mapping {
return func(w rune) rune {
m, ok := table[w]
if !ok {
return w
}
return m
}
}
//StringWithTable convert any unicode source in a LAtin compatible text using Tables conversion
func StringWithTable(source string, tables ...Table) (string, error) {
nfkd := norm.NFKD
r := runes.Remove(removeMark{})
mappers := make([]transform.Transformer, len(tables))
for idx, table := range tables {
mappers[idx] = runes.Map(replaceTable(table))
}
transformers := []transform.Transformer{
nfkd,
r,
}
transformers = append(transformers, mappers...)
// decomposity -> remove marks -> map tables
t := transform.Chain(transformers...)
res, _, err := transform.String(t, source)
return res, err
}