-
Notifications
You must be signed in to change notification settings - Fork 13
/
morse.go
81 lines (71 loc) · 1.58 KB
/
morse.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
package morse
import (
"io"
"io/ioutil"
"strings"
)
// Encoder is an interface that specifies function to Encode
type Encoder interface {
Encode(io.Reader) ([]byte, error)
}
// Decoder is an interface that specifies function to Encode
type Decoder interface {
Decode(io.Reader) ([]byte, error)
}
// Hacker is an interface that composes Encoder and Decoder
type Hacker interface {
Encoder
Decoder
}
type hacker struct {
}
func (h *hacker) Encode(r io.Reader) ([]byte, error) {
d, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
data := string(d)
data = strings.ToUpper(data)
var encodedValue string
splitData := strings.Split(data, " ")
numOfWords := len(splitData)
for j, val := range splitData {
vLen := len(val)
for i, c := range val {
char := string(c)
encodedValue += alphaNumToMorse[char]
if (i + 1) != vLen {
encodedValue += " "
}
}
if numOfWords != (j + 1) {
encodedValue += " " + "/" + " "
}
}
return []byte(encodedValue), nil
}
func (h *hacker) Decode(r io.Reader) ([]byte, error) {
d, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
data := string(d)
// strings.TrimSpace
splitData := strings.Split(data, " ")
// numOfWords := len(splitData)
var decodedValue string
for _, val := range splitData {
if val == "/" {
decodedValue += " "
}
decodedValue += morseToAlphaNum[val]
// if numOfWords == (i + 1) {
// decodedValue += " " + "/" + " "
// }
}
return []byte(decodedValue), nil
}
// NewHacker is a factory function that generates a Morse Hacker Client
func NewHacker() Hacker {
return &hacker{}
}