slice.go 871 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. }