forked from samber/slog-graylog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
54 lines (44 loc) · 1.16 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
package sloggraylog
import "golang.org/x/exp/slog"
func appendAttrsToGroup(groups []string, actualAttrs []slog.Attr, newAttrs []slog.Attr) []slog.Attr {
if len(groups) == 0 {
return uniqAttrs(append(actualAttrs, newAttrs...))
}
for i := range actualAttrs {
attr := actualAttrs[i]
if attr.Key == groups[0] && attr.Value.Kind() == slog.KindGroup {
actualAttrs[i] = slog.Group(groups[0], appendAttrsToGroup(groups[1:], attr.Value.Group(), newAttrs)...)
return actualAttrs
}
}
return uniqAttrs(
append(
actualAttrs,
slog.Group(
groups[0],
appendAttrsToGroup(groups[1:], []slog.Attr{}, newAttrs)...,
),
),
)
}
func uniqAttrs(attrs []slog.Attr) []slog.Attr {
return uniqByLast(attrs, func(item slog.Attr) string {
return item.Key
})
}
func uniqByLast[T any, U comparable](collection []T, iteratee func(item T) U) []T {
result := make([]T, 0, len(collection))
seen := make(map[U]int, len(collection))
seenIndex := 0
for _, item := range collection {
key := iteratee(item)
if index, ok := seen[key]; ok {
result[index] = item
continue
}
seen[key] = seenIndex
seenIndex++
result = append(result, item)
}
return result
}