-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.go
114 lines (92 loc) · 2.24 KB
/
input.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"unicode"
)
type DataInput struct {
Value float64
CurrencyFrom string
CurrencyTo string
}
func getInput() string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("> ")
rawInput, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
return getInput()
}
checkForQuitSequence(rawInput)
return rawInput
}
func checkForQuitSequence(input string) {
if input == ":q\n" {
os.Exit(0)
}
}
func formatInput(input string) []string {
var filterAlphanumeric = func(input string) string {
var result []rune
for _, char := range input {
if unicode.IsLetter(char) || unicode.IsDigit(char) || unicode.IsSpace(char) {
result = append(result, char)
}
}
return string(result)
}
var separateIntegerFromNumber = func(input string) []string {
var i int
for i < len(input) && unicode.IsDigit(rune(input[i])) {
i++
}
// If the word is completely digits or completely letters
if i == 0 || i == len(input) {
return []string{input}
}
return []string{input[:i], input[i:]}
}
filteredInput := filterAlphanumeric(input)
capitalizedInput := strings.ToUpper(filteredInput)
splitInput := strings.Fields(capitalizedInput)
// Build final input
var formattedInput []string
for _, word := range splitInput {
slice := separateIntegerFromNumber(word)
formattedInput = append(formattedInput, slice...)
}
return formattedInput
}
func inputWrapper(rates map[string]float64) DataInput {
var input DataInput
rawInput := getInput()
formattedInput := formatInput(rawInput)
for i := 0; i < len(formattedInput); i++ {
if input.Value == 0 {
val, err := strconv.ParseFloat(formattedInput[i], 64)
if err == nil {
input.Value = val
}
}
if checkValidCurrency(rates, formattedInput[i]) {
currentWord := formattedInput[i]
if input.CurrencyFrom == "" {
input.CurrencyFrom = currentWord
} else if input.CurrencyTo == "" {
input.CurrencyTo = currentWord
}
}
}
// If the user didn't specify value, value is 1
if input.Value == 0 {
input.Value = 1
}
if input.CurrencyFrom == "" || input.CurrencyTo == "" {
// Missing Inputs
return inputWrapper(rates)
}
return input
}