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