-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
66 lines (58 loc) · 1.17 KB
/
utils.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
package main
import "time"
func Map[T, M any](a []T, f func(T) M) []M {
n := make([]M, len(a))
for i, e := range a {
n[i] = f(e)
}
return n
}
func Filter[T any](s []T, f func(T) bool) []T {
var n []T
for _, e := range s {
if f(e) {
n = append(n, e)
}
}
return n
}
func Count[T any](slice []T, f func(T) bool) int {
count := 0
for _, s := range slice {
if f(s) {
count++
}
}
return count
}
func Reduce[T, M any](s []T, f func(M, T) M, initValue M) M {
acc := initValue
for _, v := range s {
acc = f(acc, v)
}
return acc
}
func Unique[T comparable](s []T) []T {
inResult := make(map[T]bool)
var result []T
for _, str := range s {
if _, ok := inResult[str]; !ok {
inResult[str] = true
result = append(result, str)
}
}
return result
}
func RoundTime(d time.Duration, digits int) time.Duration {
var divs = []time.Duration{
time.Duration(1), time.Duration(10), time.Duration(100), time.Duration(1000)}
switch {
case d > time.Second:
d = d.Round(time.Second / divs[digits])
case d > time.Millisecond:
d = d.Round(time.Millisecond / divs[digits])
case d > time.Microsecond:
d = d.Round(time.Microsecond / divs[digits])
}
return d
}