-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.go
More file actions
42 lines (37 loc) · 866 Bytes
/
Copy pathsort.go
File metadata and controls
42 lines (37 loc) · 866 Bytes
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
package main
import (
"sort"
"strings"
)
func sortLines(input string, desc, ignoreEmptyLines, unique bool) string {
lines := strings.Split(input, "\n")
if ignoreEmptyLines {
nonEmptyLines := make([]string, 0, len(lines))
for _, line := range lines {
if strings.TrimSpace(line) != "" {
nonEmptyLines = append(nonEmptyLines, line)
}
}
lines = nonEmptyLines
}
if unique {
lines = uniqueLines(lines)
}
if desc {
sort.Sort(sort.Reverse(sort.StringSlice(lines)))
} else {
sort.Strings(lines)
}
return strings.Join(lines, "\n")
}
func uniqueLines(lines []string) []string {
lineMap := make(map[string]struct{})
uniqueLines := make([]string, 0, len(lines))
for _, line := range lines {
if _, exists := lineMap[line]; !exists {
lineMap[line] = struct{}{}
uniqueLines = append(uniqueLines, line)
}
}
return uniqueLines
}