slice.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package slice
  2. func RemoveRepeatElement[T comparable](elements []T) []T {
  3. if elements == nil || len(elements) == 0 {
  4. return elements
  5. }
  6. result := make([]T, 0)
  7. tempMap := make(map[T]interface{})
  8. for _, element := range elements {
  9. l := len(tempMap)
  10. tempMap[element] = nil
  11. if len(tempMap) != l {
  12. result = append(result, element)
  13. }
  14. }
  15. return result
  16. }
  17. func ToMap[S any, K comparable, V any](slice []S, fn func(sliceValue S) (K, V, error)) (map[K]V, error) {
  18. m := make(map[K]V, len(slice))
  19. for _, v := range slice {
  20. key, value, err := fn(v)
  21. if err != nil {
  22. return nil, err
  23. }
  24. m[key] = value
  25. }
  26. return m, nil
  27. }
  28. func ExtractValue[T any, R any](s []T, addTo func(v T) (R, bool)) []R {
  29. retSlice := make([]R, 0)
  30. for _, v := range s {
  31. retValue, add := addTo(v)
  32. if add {
  33. retSlice = append(retSlice, retValue)
  34. }
  35. }
  36. return retSlice
  37. }
  38. func ExtractIntersectionValue[T comparable](aList, bList []T) []T {
  39. aList = RemoveRepeatElement(aList)
  40. bList = RemoveRepeatElement(bList)
  41. cList := make([]T, 0)
  42. tmpMap := make(map[T]int)
  43. for _, item := range aList {
  44. tmpMap[item] = 0
  45. }
  46. for _, item := range bList {
  47. if _, ok := tmpMap[item]; ok {
  48. cList = append(cList, item)
  49. }
  50. }
  51. return cList
  52. }
  53. func ExtractUnionValue[T comparable](aList, bList []T) []T {
  54. cList := make([]T, 0)
  55. cList = append(cList, aList...)
  56. cList = append(cList, bList...)
  57. cList = RemoveRepeatElement(cList)
  58. return cList
  59. }
  60. func ExtractASubBSetValue[T comparable](aList, bList []T) []T {
  61. aList = RemoveRepeatElement(aList)
  62. bList = RemoveRepeatElement(bList)
  63. cList := make([]T, 0)
  64. // 使用 map 标记 bList 中的元素
  65. tmpMap := make(map[T]struct{})
  66. for _, item := range bList {
  67. tmpMap[item] = struct{}{}
  68. }
  69. // 遍历 aList,将不在 bList 中的元素加入cList
  70. for _, item := range aList {
  71. if _, ok := tmpMap[item]; !ok {
  72. cList = append(cList, item)
  73. }
  74. }
  75. return cList
  76. }