sliceutil.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package sliceutil
  2. import (
  3. "iter"
  4. "slices"
  5. )
  6. // Map accepts a slice of T and applies a transformation function to each index of a
  7. // slice, which are inserted into a new slice of type U.
  8. func Map[T any, U any](s []T, transform func(T) U) []U {
  9. result := make([]U, len(s))
  10. for i := 0; i < len(s); i++ {
  11. result[i] = transform(s[i])
  12. }
  13. return result
  14. }
  15. // AsSeq converts a slice of T into an iterator sequence only yielding the values. This should be used
  16. // to convert a slice into an iterator sequence for APIs that accept iterators only.
  17. func AsSeq[T any](s []T) iter.Seq[T] {
  18. return func(yield func(T) bool) {
  19. for _, v := range s {
  20. if !yield(v) {
  21. return
  22. }
  23. }
  24. }
  25. }
  26. // AsSeq2 converts a slice of T into an iterator sequence yielding the index and value. This should be used
  27. // to convert a slice into an iterator sequence for APIs that accept iterators only.
  28. func AsSeq2[T any](s []T) iter.Seq2[int, T] {
  29. return func(yield func(int, T) bool) {
  30. for i, v := range s {
  31. if !yield(i, v) {
  32. return
  33. }
  34. }
  35. }
  36. }
  37. // SeqToSlice converts an iterator sequence into a slice of T.
  38. func SeqToSlice[T any](s iter.Seq[T]) []T {
  39. return slices.Collect(s)
  40. }