aboutsummaryrefslogtreecommitdiff
path: root/pkg/u/list.go
blob: 7271ef3783e892aad55ea49786515f491af30735 (plain)
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
package u

func First[T any](v []T) (T, bool) {
	if len(v) == 0 {
		var zero T
		return zero, false
	}
	return v[0], true
}

func FirstOrZero[T any](v []T) T {
	if len(v) == 0 {
		var zero T
		return zero
	}
	return v[0]
}

func Map[T any, V any](ts []T, fun func(T) V) []V {
	rs := make([]V, len(ts))
	for i := range ts {
		rs[i] = fun(ts[i])
	}
	return rs
}

func ChunkBy[T any](items []T, chunkSize int) [][]T {
	var chunks = make([][]T, 0, (len(items)/chunkSize)+1)
	for chunkSize < len(items) {
		items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])
	}
	return append(chunks, items)
}