diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2022-07-13 21:22:14 -0600 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2022-07-13 21:39:42 -0600 |
commit | 72a458520fccafe4df8c02c811cb6f64a310616e (patch) | |
tree | 1c424b5376c31524b01f8461b02950eb04d48345 /lib/slices/sliceutil.go | |
parent | 952b677bf7f10da93673e3671f764c54c454bbfe (diff) |
Move the remaining former-generic.go parts out of lib/util/
Diffstat (limited to 'lib/slices/sliceutil.go')
-rw-r--r-- | lib/slices/sliceutil.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/lib/slices/sliceutil.go b/lib/slices/sliceutil.go new file mode 100644 index 0000000..392514f --- /dev/null +++ b/lib/slices/sliceutil.go @@ -0,0 +1,69 @@ +// Copyright (C) 2022 Luke Shumaker <lukeshu@lukeshu.com> +// +// SPDX-License-Identifier: GPL-2.0-or-later + +package slices + +import ( + "sort" + + "golang.org/x/exp/constraints" +) + +func Contains[T comparable](needle T, haystack []T) bool { + for _, straw := range haystack { + if needle == straw { + return true + } + } + return false +} + +func RemoveAll[T comparable](haystack []T, needle T) []T { + for i, straw := range haystack { + if needle == straw { + return append( + haystack[:i], + RemoveAll(haystack[i+1:], needle)...) + } + } + return haystack +} + +func RemoveAllFunc[T any](haystack []T, f func(T) bool) []T { + for i, straw := range haystack { + if f(straw) { + return append( + haystack[:i], + RemoveAllFunc(haystack[i+1:], f)...) + } + } + return haystack +} + +func Reverse[T any](slice []T) { + for i := 0; i < len(slice)/2; i++ { + j := (len(slice) - 1) - i + slice[i], slice[j] = slice[j], slice[i] + } +} + +func Max[T constraints.Ordered](a, b T) T { + if a > b { + return a + } + return b +} + +func Min[T constraints.Ordered](a, b T) T { + if a < b { + return a + } + return b +} + +func Sort[T constraints.Ordered](slice []T) { + sort.Slice(slice, func(i, j int) bool { + return slice[i] < slice[j] + }) +} |