1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package slice
- func RemoveRepeatElement[T comparable](elements []T) []T {
- if elements == nil || len(elements) == 0 {
- return elements
- }
- result := make([]T, 0)
- tempMap := make(map[T]interface{})
- for _, element := range elements {
- l := len(tempMap)
- tempMap[element] = nil
- if len(tempMap) != l {
- result = append(result, element)
- }
- }
- return result
- }
- func ToMap[S any, K comparable, V any](slice []S, fn func(sliceValue S) (K, V, error)) (map[K]V, error) {
- m := make(map[K]V, len(slice))
- for _, v := range slice {
- key, value, err := fn(v)
- if err != nil {
- return nil, err
- }
- m[key] = value
- }
- return m, nil
- }
- func ExtractValue[T any, R any](s []T, addTo func(v T) (R, bool)) []R {
- retSlice := make([]R, 0)
- for _, v := range s {
- retValue, add := addTo(v)
- if add {
- retSlice = append(retSlice, retValue)
- }
- }
- return retSlice
- }
- func ExtractIntersectionValue[T comparable](aList, bList []T) []T {
- aList = RemoveRepeatElement(aList)
- bList = RemoveRepeatElement(bList)
- cList := make([]T, 0)
- tmpMap := make(map[T]int)
- for _, item := range aList {
- tmpMap[item] = 0
- }
- for _, item := range bList {
- if _, ok := tmpMap[item]; ok {
- cList = append(cList, item)
- }
- }
- return cList
- }
- func ExtractUnionValue[T comparable](aList, bList []T) []T {
- cList := make([]T, 0)
- cList = append(cList, aList...)
- cList = append(cList, bList...)
- cList = RemoveRepeatElement(cList)
- return cList
- }
- func ExtractASubBSetValue[T comparable](aList, bList []T) []T {
- aList = RemoveRepeatElement(aList)
- bList = RemoveRepeatElement(bList)
- cList := make([]T, 0)
- // 使用 map 标记 bList 中的元素
- tmpMap := make(map[T]struct{})
- for _, item := range bList {
- tmpMap[item] = struct{}{}
- }
- // 遍历 aList,将不在 bList 中的元素加入cList
- for _, item := range aList {
- if _, ok := tmpMap[item]; !ok {
- cList = append(cList, item)
- }
- }
- return cList
- }
|