-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.go
104 lines (84 loc) · 2.48 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
package utils
import (
"fmt"
"io"
"io/ioutil"
"strconv"
"strings"
)
// TrimmedLinesNoEmpty takes a string with the contents of a file and divides into it'elems lines.
// Whitespace is trimmed from every line.
func TrimmedLinesNoEmpty(fileContents string) []string {
var res []string
lines := strings.Split(fileContents, "\n")
for i := 0; i < len(lines); i++ {
lines[i] = strings.TrimSpace(lines[i])
if lines[i] != "" {
res = append(res, lines[i])
}
}
return res
}
// TrimmedLines takes a string with the contents of a file and divides into it'elems lines.
// Whitespace is trimmed from every line.
func TrimmedLines(fileContents string) []string {
var res []string
lines := strings.Split(fileContents, "\n")
for i := 0; i < len(lines); i++ {
lines[i] = strings.TrimSpace(lines[i])
res = append(res, lines[i])
}
return res
}
// LinesAsInts reads the string as a list of numbers.
func LinesAsInts(fileContents string) ([]int, error) {
var res []int
lines := strings.Split(fileContents, "\n")
for _, line := range lines {
l := strings.TrimSpace(line)
if l != "" {
n, err := strconv.Atoi(l)
if err != nil {
return nil, fmt.Errorf("could not convert '%v' to number: %v", line, err)
}
res = append(res, n)
}
}
return res, nil
}
// GroupByEmptyLines reads the contents fo the string and returns the lines in the file, grouped
// by empty lines separating the,
func GroupByEmptyLines(fileContents string) ([][]string, error) {
var res [][]string
lines := strings.Split(fileContents, "\n")
var partial []string
for _, line := range lines {
l := strings.TrimSpace(line)
if l == "" && len(partial) !=0 {
res = append(res, partial)
partial = []string{}
continue
}
partial = append(partial, line)
}
if len(partial) != 0 {
res = append(res, partial)
}
return res, nil
}
// GetFileAsString reads a file on the given path and returns its contents as a string with whitespace trimmed.
func GetFileAsString(filepath string) (string, error) {
data, err := ioutil.ReadFile(filepath)
if err != nil {
return "", fmt.Errorf("error reading input file as string: %w", err)
}
return strings.TrimSpace(string(data)), nil
}
// GetReaderAsString reads a file on the given path and returns its contents as a string with whitespace trimmed.
func GetReaderAsString(r io.Reader) (string, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return "", fmt.Errorf("reading all input from reader: %w", err)
}
return strings.TrimSpace(string(data)), nil
}