slice.go 641 B

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