-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsliceutils.go
101 lines (87 loc) · 1.95 KB
/
sliceutils.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
package main
import (
"fmt"
"sort"
)
// Reverse reverses any slice in place.
func Reverse(a []type T) {
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
}
// Concat returns a concatenation of multiple slices of the same type.
func Concat(slices ...[]type T) []T {
total := 0
for i := range slices {
total += len(slices[i])
}
result := make([]T, 0, total)
for i := range slices {
result = append(result, slices[i]...)
}
return result
}
// Map returns a new slice where each element from the original slice is transformed by f.
func Map(a []type T, f func(T) type U) []U {
result := make([]U, len(a))
for i := range a {
result[i] = f(a[i])
}
return result
}
// Interfaces converts a slice of an arbitrary type to a slice of empty interfaces.
func Interfaces(a []type T) []interface{} {
ifaces := make([]interface{}, len(a))
for i := range a {
ifaces[i] = a[i]
}
return ifaces
}
// Sort sorts a slice of an arbitrary orderable type.
func Sort(a []type T ord) {
sort.Slice(a, func(i, j int) bool {
return a[i] < a[j]
})
}
// SortBy sorts a slice by a key. For example:
//
// SortBy(people, (*Person).Age)
func SortBy(a []type T, by func(T) type O ord) {
sort.Slice(a, func(i, j int) bool {
return by(a[i]) < by(a[j])
})
}
// SortWith sorts a slice using a custom comparator.
func SortWith(a []type T, with func(T, T) bool) {
sort.Slice(a, func(i, j int) bool {
return with(a[i], a[j])
})
}
type Person struct {
name string
age int
}
func (p Person) Name() string {
return p.name
}
func (p Person) Age() int {
return p.age
}
func main() {
people := []Person{
{"Michal", 23},
{"Viktória", 20},
{"Jano", 21},
{"Martin", 18},
}
SortBy(people, Person.Age)
fmt.Println(people)
names := Map(people, Person.Name)
ages := Map(people, Person.Age)
ageStrings := Map(ages, func(a int) string {
return fmt.Sprint(a)
})
everything := Concat(names, ageStrings)
Reverse(everything)
fmt.Println(everything)
}