You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

slice.go 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import (
  5. "slices"
  6. "strings"
  7. )
  8. // SliceContainsString sequential searches if string exists in slice.
  9. func SliceContainsString(slice []string, target string, insensitive ...bool) bool {
  10. if len(insensitive) != 0 && insensitive[0] {
  11. target = strings.ToLower(target)
  12. return slices.ContainsFunc(slice, func(t string) bool { return strings.ToLower(t) == target })
  13. }
  14. return slices.Contains(slice, target)
  15. }
  16. // SliceSortedEqual returns true if the two slices will be equal when they get sorted.
  17. // It doesn't require that the slices have been sorted, and it doesn't sort them either.
  18. func SliceSortedEqual[T comparable](s1, s2 []T) bool {
  19. if len(s1) != len(s2) {
  20. return false
  21. }
  22. counts := make(map[T]int, len(s1))
  23. for _, v := range s1 {
  24. counts[v]++
  25. }
  26. for _, v := range s2 {
  27. counts[v]--
  28. }
  29. for _, v := range counts {
  30. if v != 0 {
  31. return false
  32. }
  33. }
  34. return true
  35. }
  36. // SliceRemoveAll removes all the target elements from the slice.
  37. func SliceRemoveAll[T comparable](slice []T, target T) []T {
  38. return slices.DeleteFunc(slice, func(t T) bool { return t == target })
  39. }
  40. // TODO: Replace with "maps.Keys" once available, current it only in golang.org/x/exp/maps but not in standard library
  41. func KeysOfMap[K comparable, V any](m map[K]V) []K {
  42. keys := make([]K, 0, len(m))
  43. for k := range m {
  44. keys = append(keys, k)
  45. }
  46. return keys
  47. }