aboutsummaryrefslogtreecommitdiff
path: root/pkg/list/list.go
blob: 8f3d875fb4b6fc17202dabaab72642ea5f0b41f2 (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
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
package list

func Map[V any, T any](source []V, fun func(V) T) []T {
	result := make([]T, 0, len(source))
	for _, s := range source {
		result = append(result, fun(s))
	}
	return result
}

type Pair[T, U any] struct {
	Left  T
	Right U
}

func Distribuite[T any](slice []T, size int) [][]T {
	chuncks := make([][]T, size)

	for i := 0; i < len(slice); i += size {
		for x := 0; x < size; x++ {
			end := i + x

			if end >= len(slice) {
				return chuncks
			}

			chuncks[x] = append(chuncks[x], slice[end])
		}
	}

	return chuncks
}

func Chunck[T any](slice []T, size int) [][]T {
	var divided [][]T

	chunkSize := (len(slice) + size - 1) / size

	for i := 0; i < len(slice); i += chunkSize {
		end := i + chunkSize

		if end > len(slice) {
			end = len(slice)
		}

		divided = append(divided, slice[i:end])
	}

	return divided
}

func Zip[T, U any](left []T, right []U) []Pair[T, U] {
	// pick the array with the smaller length
	l := len(left)
	if len(left) > len(right) {
		l = len(right)
	}

	pairs := make([]Pair[T, U], len(left))
	for i := 0; i < l; i++ {
		pairs[i] = Pair[T, U]{left[i], right[i]}
	}
	return pairs
}

func Revert[T any](s []T) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}