aboutsummaryrefslogtreecommitdiff
path: root/go/utils/slices.go
blob: d12b4ee06f9e9b6f8b5a5d88414a26588f66dfb6 (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
package utils

func TypedSliceToInterfaceSlice[T any](s []T) []any {
	is := make([]any, 0, len(s))
	for _, t := range s {
		is = append(is, t)
	}
	return is
}

func InterfaceSliceToTypedSlice[T any](s []any) []T {
	ts := make([]T, 0, len(s))
	for _, t := range s {
		ts = append(ts, t.(T))
	}
	return ts
}

func InterfaceSliceContains[T comparable](s []any, o T) bool {
	for _, _t := range s {
		switch t := _t.(type) {
		case T:
			if t == o {
				return true
			}
		}
	}
	return false
}

func RemoveFromUnorderedSlice[T comparable](s []T, o T) []T {
	for i, t := range s {
		if t != o {
			continue
		}

		s[i] = s[len(s) - 1]
		return s[:len(s) - 1]
	}

	return s
}