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.9KB

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