iterutil.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package iterutil
  2. import "iter"
  3. // Combine takes two iterator sequences and combines them into a single iterator sequence of pairs.
  4. // This iterator will only yield as many values as the smallest of the two sequences.
  5. func Combine[T any, U any](seq1 iter.Seq[T], seq2 iter.Seq[U]) iter.Seq2[T, U] {
  6. return func(yield func(T, U) bool) {
  7. n1, s1 := iter.Pull(seq1)
  8. n2, s2 := iter.Pull(seq2)
  9. defer s1()
  10. defer s2()
  11. for {
  12. first, fOk := n1()
  13. if !fOk {
  14. return
  15. }
  16. second, sOk := n2()
  17. if !sOk {
  18. return
  19. }
  20. if !yield(first, second) {
  21. return
  22. }
  23. }
  24. }
  25. }
  26. // Concat takes multiple iterator sequences and concatenates them into a single iterator sequence.
  27. // This iterator will yield all values from the first sequence, followed by all values from the second
  28. // sequence, and so on.
  29. func Concat[T any](seqs ...iter.Seq[T]) iter.Seq[T] {
  30. return func(yield func(T) bool) {
  31. for _, seq := range seqs {
  32. func() {
  33. n, s := iter.Pull(seq)
  34. defer s()
  35. for {
  36. v, ok := n()
  37. if !ok || !yield(v) {
  38. return
  39. }
  40. }
  41. }()
  42. }
  43. }
  44. }