Core

/app/util/array.go (2.4 KB)

  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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package util

import (
"cmp"
"fmt"
"reflect"
"slices"

"github.com/samber/lo"
)

func StringArrayMaxLength(a []string) int {
return len(lo.MaxBy(a, func(x string, max string) bool {
return len(x) > len(max)
}))
}

func StringArrayQuoted(a []string) []string {
return lo.Map(a, func(x string, _ int) string {
return fmt.Sprintf("%q", x)
})
}

func StringArrayFromInterfaces(a []any, maxLength int) []string {
ret := make([]string, 0, len(a))
lo.ForEach(a, func(x any, _ int) {
var v string
switch t := x.(type) {
case string:
v = t
case []byte:
v = string(t)
default:
v = fmt.Sprint(x)
}
if maxLength > 0 && len(v) > maxLength {
v = v[:maxLength] + "... (truncated)"
}
ret = append(ret, v)
})
return ret
}

func ArrayRemoveDuplicates[T comparable](x []T) []T {
return lo.Uniq(x)
}

func ArraySorted[T cmp.Ordered](x []T) []T {
slices.Sort(x)
return x
}

func InterfaceArrayFrom[T any](x ...T) []any {
return lo.Map(x, func(item T, idx int) any {
return item
})
}

func StringArrayOxfordComma(names []string, separator string) string {
ret := ""
lo.ForEach(names, func(name string, idx int) {
if idx > 0 {
if idx == (len(names) - 1) {
if idx > 1 {
ret += ","
}
ret += " " + separator + " "
} else {
ret += ", "
}
}
ret += name
})
return ret
}

func ArrayRemoveNil[T any](x []*T) []*T {
return lo.Reject(x, func(item *T, _ int) bool {
return item == nil
})
}

func ArrayDereference[T any](x []*T) []T {
return lo.Map(x, func(item *T, _ int) T {
return lo.FromPtr(item)
})
}

func LengthAny(dest any) int {
defer func() { _ = recover() }()
rfl := reflect.ValueOf(dest)
if rfl.Kind() == reflect.Ptr {
rfl = rfl.Elem()
}
return rfl.Len()
}

func ArrayFromAny(dest any) []any {
defer func() { _ = recover() }()
rfl := reflect.ValueOf(dest)
if rfl.Kind() == reflect.Ptr {
rfl = rfl.Elem()
}
if k := rfl.Kind(); k == reflect.Array || k == reflect.Slice {
return lo.Times(rfl.Len(), func(i int) any {
return rfl.Index(i).Interface()
})
}
return []any{dest}
}

func ArrayFlatten[T any](arrs ...[]T) []T {
return lo.Flatten(arrs)
}

func ArrayFirstN[V any](items []V, n int) []V {
if n > len(items) {
return items
}
return items[:n]
}

func ArrayLastN[V any](items []V, n int) []V {
if n > len(items) {
return items
}
return items[len(items)-n:]
}