-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspellabc.go
77 lines (64 loc) · 2.16 KB
/
spellabc.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
// Copyright (c) 2012 Aaron Bull Schaefer
// This source code is provided under the terms of the MIT License
// that can be be found in the LICENSE file.
// Package spellabc implements spelling alphabet code word encoding.
package spellabc
import (
"strings"
"unicode"
)
// An Encoding is a character to code word mapping scheme, defined by a
// spelling alphabet. The most common is the "NATO" spelling alphabet.
type Encoding struct {
alphabet map[rune]string
}
// NewEncoding returns a new Encoding defined by the given alphabet.
func NewEncoding(encoder map[rune]string) *Encoding {
e := new(Encoding)
e.alphabet = encoder
return e
}
// JanAlphabet is the Joint Army/Navy phonetic alphabet.
var JanAlphabet = NewEncoding(encodeJan)
// LapdAlphabet is the LAPD phonetic alphabet.
// It is also known as the APCO phonetic alphabet.
var LapdAlphabet = NewEncoding(encodeLapd)
// NatoAlphabet is the NATO phonetic alphabet.
// It is also known as the International Radiotelephony Spelling Alphabet
// and the ICAO spelling alphabet.
var NatoAlphabet = NewEncoding(encodeNato)
// UsFinancialAlphabet is the US Financial phonetic alphabet.
var UsFinancialAlphabet = NewEncoding(encodeUsFinancial)
// WesternUnionAlphabet is the Western Union phonetic alphabet.
var WesternUnionAlphabet = NewEncoding(encodeWesternUnion)
// codeWordFor returns the spelling alphabet code word for r.
// If r is not defined in the alphabet, returns r.
func (enc *Encoding) codeWordFor(r rune) string {
word, ok := enc.alphabet[unicode.ToLower(r)]
if !ok {
return string(r)
}
switch {
case unicode.IsLower(r):
word = strings.ToLower(word)
case unicode.IsUpper(r):
word = strings.ToUpper(word)
}
return word
}
func (enc *Encoding) encodeLine(s string) string {
dst := make([]string, len(s))
for index, char := range []rune(s) {
dst[index] = enc.codeWordFor(char)
}
return strings.Join(dst, " ")
}
// Encode converts s into its spelling alphabet representation, defined by enc.
func (enc *Encoding) Encode(s string) string {
lines := strings.Split(s, "\n")
dst := make([]string, len(lines))
for index, line := range lines {
dst[index] = enc.encodeLine(line)
}
return strings.Join(dst, "\n")
}